Biến ra trước tiên bạn cần mạo danh người dùng.
Sử dụng thư viện rất đẹp mô tả trong A small C# Class for impersonating a User, bạn có thể làm như sau:
using (new Impersonator("username", "", "password"))
{
try
{
X509Store serviceRuntimeUserCertificateStore = new X509Store(StoreName.My);
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string certPath = Path.Combine(baseDir, certificateFolder);
string certificateFile = "c:\\file.cert";
string certificatePassword = "somePassword";
string certificateLocation = certPath + "\\" + certificateFile;
InstallCertificate(certificateLocation, certificatePassword);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static void InstallCertificate(string certificatePath, string certificatePassword)
{
try
{
var serviceRuntimeUserCertificateStore = new X509Store(StoreName.My);
serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);
X509Certificate2 cert;
try
{
cert = new X509Certificate2(certificatePath, certificatePassword);
}
catch(Exception ex)
{
Console.WriteLine("Failed to load certificate " + certificatePath);
throw new DataException("Certificate appeared to load successfully but also seems to be null.", ex);
}
serviceRuntimeUserCertificateStore.Add(cert);
serviceRuntimeUserCertificateStore.Close();
}
catch(Exception)
{
Console.WriteLine("Failed to install {0}. Check the certificate index entry and verify the certificate file exists.", certificatePath);
}
}
Vui lòng thêm xử lý ngoại lệ của riêng bạn. Nếu bạn đang thêm nhiều chứng chỉ, hãy giữ cho X509Store mở trong suốt thời gian hiệu quả.
Bạn có nghĩ rằng lý do bạn phải mạo danh người dùng là vì bạn cần quyền đọc khóa riêng tư không? Nếu vậy bạn có thể có thể thêm quyền sau này nếu bạn hoàn toàn phải. –