C# で証明書を証明書ストアにインストールする

.pfx ファイルとパスワードを指定して、証明書ストアにインストールするサンプル。

using System;
using System.Security.Cryptography.X509Certificates;

namespace InstallCertSample
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine($"使い方: {nameof(InstallCertSample)}.exe <certFilePath> <password>");
                return;
            }

            // インストールする証明書ファイルのパス
            var certFilePath = args[0];

            // インストールする証明書ファイルのパスワード
            var password = args[1];

            try
            {
                // 証明書ストアを開く
                using (var store = new X509Store(storeName: StoreName.My, storeLocation: StoreLocation.CurrentUser))
                {
                    store.Open(OpenFlags.ReadWrite);

                    // 証明書ファイルを読み込む
                    // サーバー証明書で使いたいのでキーは保持させる
                    var certificate = new X509Certificate2(
                        fileName: certFilePath,
                        password: password,
                        keyStorageFlags: X509KeyStorageFlags.PersistKeySet);

                    // 証明書をストアにインストール
                    store.Add(certificate);

                    Console.WriteLine("証明書インストール成功");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("証明書インストールエラー: " + ex.Message);
            }
        }
    }
}