将证书添加到x509Store不会做任何事情C#

时间:2014-12-12 12:17:06

标签: c# x509certificate x509 certificate-store

我试图添加证书,但添加功能似乎没有做任何事情。

我有两张证书。我可以通过右键单击并保存到个人" testStore"手动添加。存储,但当我尝试以编程方式添加它们时,它们不会被保存。我甚至只添加其中一个,X509Store对象包含它就像预期的那样,但是当我调用.Add(cert)时,没有任何东西保存在那里。

//I've already added 1 cert manually
X509Certificate2 cert2 = new X509Certificate2(@"C:\temp\Cert2.cer");
X509Store store = new X509Store("testStore", StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);

//here store.Certificates has the one Certificate I added manually as expected.

store.Certificates.Add(cert2);

//here store.Certificates still only has the first certificate, cert2 still isn't there..

store.Close();

我错过了什么吗?

编辑 我也尝试使用StorePermission(如下所示)并尝试模拟管理员帐户,但这些都没有帮助

StorePermission sp = new StorePermission( PermissionState.Unrestricted);
sp.Flags = StorePermissionFlags.AllFlags;
sp.Assert();

2 个答案:

答案 0 :(得分:2)

我让它工作......事实证明你应该使用store.Add()而不是store.Certificates.Insert();

//When LocalMachine is used, .Add() requires that you run the app as an administrator in order to work.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
X509Certificate2 cert = new X509Certificate2("C:\\test\\test.cer");
store.Open(OpenFlags.MaxAllowed);
store.Add(cert);
store.Close();

答案 1 :(得分:1)