如何检查是否安装了证书

时间:2014-06-10 13:04:54

标签: c# certificate

我刚开始使用.NET和C#。我正在尝试检查是否有计算机证书。它是一个具体的无线证书。

到目前为止,这是我的代码:

public void Analyser_Load(object sender, EventArgs e)
{
    X509Store store = new X509Store(StoreLocation.LocalMachine);
    X509Certificate2Collection col = store.Certificates
        .Find(X509FindType.FindBySubjectName, "MyCertName", false);
}

2 个答案:

答案 0 :(得分:1)

这有效:

X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);

var certificates = store.Certificates.Find(
    X509FindType.FindBySubjectName, 
    "subjectName", 
    false);

if (certificates != null && certificates.Count > 0)
{
   Console.WriteLine("Certificate already exists");
}

答案 1 :(得分:-1)

如果找不到证书,集合本身将为空。

if(col.Count > 0) {
    // Cert found!
}

我获取证书的方法:

X509Store store = new X509Store("My", StoreLocation.CurrentUser);
X509Certificate2 cert = default(cert);
try
{
    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
    X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates.Find(X509FindType.FindBySubjectName, "find.my@cert.com", true);
    cert = collection[0];
}
catch(Exception e)
{
    throw new Exception("Error while fetching certificate. Please check that the application user can access the store.\r\n" + e.Message);
}
finally
{
    store.Close();
}