Loading .cer files
The following example demonstrates how a typical program would load a certificate file. This example can load DER encoded certificates [that are optionally Base64 encoded], PKCS#7 signed messages and serialized certificate stores. These types of certificates are usually stored in files with a .cer extension. To load a PFX/P12 file, take a look at this example code.
using System;
using System.IO;
using Org.Mentalis.Security.Certificates;
/// <summary>
/// Loads a certificate from a certificate file.
/// </summary>
/// <param name="filename">The file that contains the certificate.</param>
/// <returns>A Certificate instance.</returns>
/// <exception cref="ArgumentNullException">filename is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="FileNotFoundException">filename could not be found on
/// the hard disk.</exception>
/// <exception cref="CertificateException">An error occurs while opening the
/// certificate store.</exception>
public Certificate LoadCerFile(string filename) {
if (filename == null)
throw new ArgumentNullException("filename", "Invalid argument.");
if (!File.Exists(filename))
throw new FileNotFoundException("Couldn't find the certificate file.");
// open the file and convert it to a CertificateStore instance
CertificateStore store = CertificateStore.CreateFromCerFile(filename);
// find the first certificate in the store
// if no certificate is found, this method return 'null'
Certificate cert = store.FindCertificate();
if (cert == null)
throw new CertificateException("The specified store is empty.");
return cert;
}