I have created code to delete pfx certificate is given below,
X509Store store = new X509Store(
StoreName.Root, StoreLocation.LocalMachine
);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection =
(X509Certificate2Collection)store.Certificates;
X509Certificate2Collection fcollection =
(X509Certificate2Collection)collection.Find(
X509FindType.FindBySubjectName,
"CN=AWS IoT Certificate", false
);
foreach (X509Certificate2 x509 in fcollection)
{
byte[] rawdata = x509.RawData;
Console.WriteLine(
"Friendly Name: {0}{1}",
x509.FriendlyName, Environment.NewLine
);
Console.WriteLine(
"Simple Name: {0}{1}",
x509.GetNameInfo(X509NameType.SimpleName, true),
Environment.NewLine
);
store.Remove(x509);
Console.WriteLine(
"X509Certificate2 for localhost removed."
);
}
store.Close();
But in the fcollection variable, didn't get certificate collection with subject name. Here =>
X509Certificate2Collection fcollection =
(X509Certificate2Collection)collection.Find(
X509FindType.FindBySubjectName,
"CN=AWS IoT Certificate", false
);
How to get certificate collection. collection count getting zero.
X509FindType.FindBySubjectName
expects a subject name without RDN attribute: "CN=AWS IoT Certificate" -> "AWS IoT Certificate"
. And make sure if certificate is indeed in the store.
In addition:
store.Open(OpenFlags.ReadOnly)
you are opening store in read-only mode. You can't modify the store using this flag.