Consider the following code:
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
if (!string.IsNullOrWhiteSpace(certificate?.SubjectName?.Name)
&& certificate.SubjectName.Name.StartsWith("CN=*.mysite.com"))
{
return certificate;
}
}
}
So I can clearly loop through the certificates, but why can't I enumerate them. Why does the following code throw compilation errors?
var cert = store.Certificates.FirstOrDefault(x =>
string.IsNullOrWhiteSpace(x?.SubjectName?.Name) &&
x.SubjectName.Name.StartsWith("CN=*.mysite.com"));
Error CS1061 'X509Certificate2Collection' does not contain a definition for 'FirstOrDefault' and no accessible extension method 'FirstOrDefault' accepting a first argument of type 'X509Certificate2Collection' could be found (are you missing a using directive or an assembly reference?)
You should cast it to be able to use it:
store.Certificates.OfType<X509Certificate2>().FirstOrDefault(x =>
string.IsNullOrWhiteSpace(x?.SubjectName?.Name) &&
x.SubjectName.Name.StartsWith("CN=*.mysite.com"));
store.Certificates.Cast<X509Certificate2>()
will give you an IEnumerable<X509Certificate2>
which is what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With