When I execute CryptFindLocalizedName more than once from my .Net code it comes back with invalid information. The first call is accurate but any subsequence calls using the same string returns bad data. I am not an expert on using the Win32 api in C# so I could be doing something wrong.
Here is my code…
[DllImport("cryp32.dll", CharSet = CharSet.Auto]
public static extern string CryptFindLocalizedName(
[In] string pwszCryptName
);
public static void Test()
{
Console.WriteLine(CryptFindLocalizedName("My")); // Returns "Personal"
Console.WriteLine(CryptFindLocalizedName("My")); // Returns "<weirdchar>ersonal"
}
I am trying to return the Friendly Names to the certificate stores.
What am I doing wrong?
The problem is presumably that the marshaller is doing something it should not with the return value. The MSDN documentation states:
But the C# marshaller doesn’t know that. Instead you’ll need to take control over the marshalling of the return value.
For simplicity I’ve ignored error handling, but this is the essence of your problem.
The documentation for
PtrToStringUnistates:In other words, it doesn’t free the return value from
CryptFindLocalizedNameand that’s exactly what you want in this situation.