title: How to load another's certificate to my local certificate store?
body: <p>I have a certificate (.pem file) that is distributed by another service vendor. I downloaded the certificate from the vendor and saved it to my local drive. In my WCF client, I am trying to load this certificate from the local drive and it is giving me an error “The private key is not present in the X.509 certificate” when communicating with the service. I was told that I need to load this certificate to my local certificate store to resolve this error. Can anyone provide some directions? Thanks!</p>
  
  <p>I have the below function to load certificate from the path specified in the file parameter.</p>
  
  <pre><code>public static X509Certificate LoadCertificate(string file)
      {
          try
          {
              return X509Certificate.CreateFromCertFile(file);
          }
          catch (System.Security.Cryptography.CryptographicException)
          {
              string filestr = File.ReadAllText(file);
  
              StringBuilder sb = new StringBuilder(filestr.Remove(0, filestr.IndexOf("-----BEGIN CERTIFICATE-----")));
  
              sb.Replace("-----BEGIN CERTIFICATE-----", "");
              sb.Replace("-----END CERTIFICATE-----", "");
              //Decode 
              try
              {        //see if the file is a valid Base64 encoded cert
                  byte[] certBytes = Convert.FromBase64String(sb.ToString());
  
                  return new X509Certificate(certBytes);
              }
              catch (System.FormatException)
              {
                  throw;
              }
          }
      }
  </code></pre>
  
  <p>In my WCF client, it is loading the certificate that was created from LoadCertificate() function.</p>
  
  <pre><code>    public X509Certificate Certificate { get; set; }
  
      ClientCredentials loginCredentials = new ClientCredentials();
      loginCredentials.UserName.UserName = this.UserId;
      loginCredentials.UserName.Password = this.Password;
      loginCredentials.ClientCertificate.Certificate = new X509Certificate2(this.Certificate);
  </code></pre>