I am using this code to find the certificate by its thumbprint. certificate exists in certificate manager in personal certificate store but this code is not finding that certificate.
Please tell me where I'm doing wrong in it.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string certThumbPrint = "fe14593dd66b2406c5269d742d04b6e1ab03adb1";
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
// Try to open the store.
certStore.Open(OpenFlags.ReadOnly);
// Find the certificate that matches the thumbprint.
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint, certThumbPrint, false);
certStore.Close();
// Check to see if our certificate was added to the collection. If no,
// throw an error, if yes, create a certificate using it.
if (0 == certCollection.Count)
{
Console.WriteLine("Error: No certificate found containing thumbprint " );
}
Console.ReadLine();
}
Just stumbled over this question when Googling for the same issue, and found the answer here: if, like me, you obtained your "source" thumbprint from MMC by highlighting the thumbprint and copying it to the clipboard, you've almost certainly caught an invisible character at the start of the screen, so:
string certThumbPrint = "fe14593dd66b2406c5269d742d04b6e1ab03adb1";
is actually
string certThumbPrint = "INVISIBLECHARACTERfe14593dd66b2406c5269d742d04b6e1ab03adb1";
If you delete this invisible character (you can tell it's there when you press backspace or delete beside it and nothing seems to happen), or just retype the thumbprint by hand, your code should work fine. Now if only Visual Studio had a "show invisible characters" option ...