Validating the Certificate Chain

Ususally when tesitng with different certificates we usually need to check if the certificate chain is valid and this snippet came in quite handy in many places.


static bool BuildChain(){        X509Certificate2 cert = LookupCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=Localhost");        X509Chain chain = new X509Chain();            return chain.Build(cert); }static X509Certificate2 LookupCertificate(StoreName storeName,                                        StoreLocation storeLocation,                                        string subjectDistinguishedName){    X509Store store = null;    try    {        store = new X509Store(storeName, storeLocation);        store.Open(OpenFlags.ReadOnly);        X509Certificate2Collection certs =             store.Certificates.Find(                    X509FindType.FindBySubjectDistinguishedName,                    subjectDistinguishedName,                     false);        if (certs.Count != 1)        {            throw new Exception("Certificate not found or more than one certificate found");        }        return (X509Certificate2)certs[0];    }    finally    {        if (store != null)             store.Close();    }}