考虑以下代码:
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;
}
}
}
所以我可以清楚地遍历证书,但为什么我不能枚举它们。为什么下面的代码会抛出编译错误?
var cert = store.Certificates.FirstOrDefault(x =>
string.IsNullOrWhiteSpace(x?.SubjectName?.Name) &&
x.SubjectName.Name.StartsWith("CN=*.mysite.com"));
最佳答案
您应该转换它才能使用它:
store.Certificates.OfType<X509Certificate2>().FirstOrDefault(x =>
string.IsNullOrWhiteSpace(x?.SubjectName?.Name) &&
x.SubjectName.Name.StartsWith("CN=*.mysite.com"));
store.Certificates.Cast<X509Certificate2>()
会给你一个 IEnumerable<X509Certificate2>
这是你需要的。关于c# - 为什么我不能枚举 X509Store.Certificates,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55327694/