Erez Erez - 1 year ago 111
C# Question

How to get certificate from specific binding C#

I found on the internet only way to got all the certificates from the iis and i do it like the following (c#):

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

Now I try to get a specific certificate of specific binding, how can I do it in C#?

Answer Source

The certificates themselves hold absolutely no information about the bindings used in IIS, so you cannot retrieve the certificates from the machine and expect them to have anything related to IIS. You would need to query that information from IIS.

To do this, you will need add a reference to the library that can be found under %windir%\system32\inetsrv\Microsoft.Web.Administration.dll (note: IIS 7 or newer must be installed). After this, you can do something like the following to get the certificate (this was not tested, so a some modifications might be required):

ServerManager manager = new ServerManager();
Site yourSite = manager.Sites["yourSiteName"];

X509Certificate2 yourCertificate = null;

foreach (Binding binding in yourSite.Bindings)
    if (binding.Protocol == "https" && binding.EndPoint.ToString() == "" /*your binding IP*/)
        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        yourCertificate = store.Certificates.Find(X509FindType.FindByThumbprint, System.Convert.ToBase64String(binding.CertificateHash), true)[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download