How to retrieve all certificates in your X509Store

Pablo picture Pablo · Jan 18, 2011 · Viewed 65.5k times · Source

I am using the following code to retrieve all certificates in my PC from an asp.net webapp. The certificates collection is empty, and I can't understand why.

I tried impersonating my own user account and I didn't succeed as well. What am I doing wrong?

var store = new X509Store(StoreLocation.CurrentUser); //StoreLocation.LocalMachine fails too
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
    var friendlyName = certificate.FriendlyName;
    Console.WriteLine(friendlyName);
}

//original problem: fetch a single certificate by its subject name
X509Certificate2 clientCertificate = CertificateUtility.GetCertificate(StoreName.My, StoreLocation.CurrentUser,  "CN=mypc.domainname"); //returns null :(

Answer

Chris B. Behrens picture Chris B. Behrens · Jan 18, 2011

Add this line of code to the second line and see how it works:

store.Open(OpenFlags.ReadOnly);

and then this at the bottom :):

store.Close();