Intermittent error "The system cannot find the file specified" when instantiating X509Certificate2
URL(s)
https://github.com/dotnet/core/blob/main/release-notes/6.0/6.0.0/6.0.0.md
Description
I have this method in a .NET (net6.0) application, to instantiate and return a digital certificate.
using framework.mstiCSharp.Extensions;
using System;
using System.Security.Cryptography.X509Certificates;
namespace msti.newpro.Core.Services.ADMServices.Services
{
public static class DigitalServices Certificate
{
public static X509Certificate2 GetX509Certificate2(string Base64Certificate, string Password)
{
try
{
byte[] decodedByteArray = Convert.FromBase64String(Base64Certificate);
return new X509Certificate2(decodedByteArray, Password);
}
catch (Exception ex)
{
throw new Exception("Error loading digital certificate: " + ex.GetAllInnerExceptionMessage() + "\n"+ "Base64: "+ Base64Certificate);
}
}
}
}
Most of the time, it works fine. But sometimes and only sometimes, it throws the exception:
"The system cannot find the file specified"
I generated logs of the input parameters (Base64Certificate string, Password string) and there is no problem with them, they always have the expected values.
In the testing environment and on my local computer, we never had the problem. But in production, on an AWS EC2, running Windows Server 2019, we sometimes have this problem.
Have a look at these https://github.com/dotnet/runtime/issues/25143 https://briandunnington.github.io/create_certificate_from_bytes
I guess you run in IIS We made a workaround Select Advanced settings for apppool In "Process model" set "Load user profile" to TRUE.