Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I enumerate X509Store.Certificates

Tags:

c#

linq

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?)

like image 282
Bagzli Avatar asked Jan 27 '23 13:01

Bagzli


1 Answers

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.

like image 121
Ashkan Mobayen Khiabani Avatar answered Jan 29 '23 04:01

Ashkan Mobayen Khiabani