たかやまのプログラミング

プログラミング中心のブログです。

C#のMicrosoft.Win32.RegistryKeyクラスを使用して拡張子登録

takym.code.blog


この記事はhttps://takymsystems.blog.fc2.com/blog-entry-59.htmlに転載しました。
リメイク版の記事ができましたのでこちらの記事を見てください。
C#で拡張子を登録する方法を見つけました。
C#Microsoft.Win32.RegistryKeyクラスを使用します。


Extension.cs

using Microsoft.Win32;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Sample
{
    public class Extension
    {
        public Extension()
        {
            // 登録する拡張子。
            // (※お好みで指定してください。)
            string extension = ".test";

            // 実行するコマンドライン。
            string commandline = "\"" + Application.ExecutablePath + "\" \"%1\"";
            string fileType = Application.ProductName;

            // 説明。
            // (※お好みで指定してください。)
            string description = "test ファイル";

            // 動詞。
            // (※お好みで指定してください。)
            string verb = "open";
            string verbDescription = "開く(&O)";

            // アイコンの指定。
            string iconPath = Application.ExecutablePath;
            int iconIndex = 0;


            // ※以下のコードは書き変えないで使ってください。
            RegistryKey rootkey = Registry.ClassesRoot;

            RegistryKey regkey = rootkey.CreateSubKey(extension);
            regkey.SetValue("", fileType);
            regkey.Close();

            RegistryKey typekey = rootkey.CreateSubKey(fileType);
            typekey.SetValue("", description);
            typekey.Close();

            RegistryKey verblkey = rootkey.CreateSubKey(fileType + "\\shell\\" + verb);
            verblkey.SetValue("", verbDescription);
            verblkey.Close();

            RegistryKey cmdkey = rootkey.CreateSubKey(fileType + "\\shell\\" + verb + "\\command");
            cmdkey.SetValue("", commandline);
            cmdkey.Close();

            RegistryKey iconkey = rootkey.CreateSubKey(fileType + "\\DefaultIcon");
            iconkey.SetValue("", iconPath + "," + iconIndex.ToString());
            iconkey.Close();
        }
    }
}



ソースコードのダウンロード