C# 如何将文件扩展名与C中的当前可执行文件关联#

C# 如何将文件扩展名与C中的当前可执行文件关联#,c#,windows,winforms,C#,Windows,Winforms,我想将文件扩展名与C#中的当前可执行文件相关联。 这样,当用户在资源管理器中单击该文件后,它将以给定文件作为第一个参数运行我的可执行文件。 理想情况下,它还会将给定文件扩展名的图标设置为可执行文件的图标。 谢谢大家。文件关联在注册表的HKEY_CLASSES_根目录下定义 有一个VB.NET示例,我很高兴您可以轻松地将其移植到C#。似乎没有用于直接管理文件关联的.NET API,但您可以使用注册表类来读取和写入所需的键 您需要在HKEY_CLASSES_ROOT下创建一个密钥,其名称设置为您的文

我想将文件扩展名与C#中的当前可执行文件相关联。 这样,当用户在资源管理器中单击该文件后,它将以给定文件作为第一个参数运行我的可执行文件。 理想情况下,它还会将给定文件扩展名的图标设置为可执行文件的图标。
谢谢大家。

文件关联在注册表的HKEY_CLASSES_根目录下定义


有一个VB.NET示例,我很高兴您可以轻松地将其移植到C#。

似乎没有用于直接管理文件关联的.NET API,但您可以使用注册表类来读取和写入所需的键

您需要在HKEY_CLASSES_ROOT下创建一个密钥,其名称设置为您的文件扩展名(例如:“.txt”)。将此键的默认值设置为文件类型的唯一名称,例如“Acme.TextFile”。然后在HKEY_CLASSES_ROOT下创建另一个密钥,名称设置为“Acme.TextFile”。添加名为“DefaultIcon”的子项,并将该项的默认值设置为包含要用于此文件类型的图标的文件。添加另一个名为“shell”的兄弟。在“shell”键下,为希望通过资源管理器上下文菜单提供的每个操作添加一个键,将每个键的默认值设置为可执行文件的路径,后跟空格和“%1”以表示所选文件的路径

例如,下面是一个示例注册表文件,用于在.txt文件和EmEditor之间创建关联:

Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\.txt] @="emeditor.txt" [HKEY_CLASSES_ROOT\emeditor.txt] @="Text Document" [HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon] @="%SystemRoot%\\SysWow64\\imageres.dll,-102" [HKEY_CLASSES_ROOT\emeditor.txt\shell] [HKEY_CLASSES_ROOT\emeditor.txt\shell\open] [HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command] @="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" \"%1\"" [HKEY_CLASSES_ROOT\emeditor.txt\shell\print] [HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command] @="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" /p \"%1\"" Windows注册表编辑器5.00版 [HKEY_CLASSES_ROOT\.txt] @=“emeditor.txt” [HKEY\U CLASSES\U ROOT\emeditor.txt] @=“文本文档” [HKEY\U CLASSES\U ROOT\emeditor.txt\DefaultIcon] @=%SystemRoot%\\SysWow64\\imageres.dll,-102 [HKEY\U CLASSES\U ROOT\emeditor.txt\shell] [HKEY\U CLASSES\U ROOT\emeditor.txt\shell\open] [HKEY\U CLASSES\U ROOT\emeditor.txt\shell\open\command] @=“C:\\Program Files\\EmEditor\\EmEditor.EXE\”\%1“ [HKEY\U CLASSES\U ROOT\emeditor.txt\shell\print] [HKEY\U CLASSES\U ROOT\emeditor.txt\shell\print\command] @=“C:\\Program Files\\EmEditor\\EmEditor.EXE\”/p\%1“
此外,如果您决定使用注册表方式,请记住当前用户关联位于HKEY\U current\U user\Software\Classes下。最好将应用程序添加到那里,而不是本地机器类


如果您的程序将由有限的用户运行,您将无法修改类\u根目录。

您选择不在项目中使用安装包可能有特定的原因,但安装包是轻松执行应用程序配置任务(如注册文件扩展名、添加桌面快捷方式、,等等

以下是如何使用内置的Visual Studio安装工具创建文件扩展名关联:

  • 在现有的C#解决方案中,添加一个新项目并选择项目类型为
    其他项目类型
    ->
    设置和部署
    ->
    设置项目
    (或尝试安装向导)

  • 配置您的安装程序(如果您需要帮助,可以使用大量现有文档)

  • 右键单击解决方案资源管理器中的安装项目,选择
    查看
    ->
    文件类型
    ,然后添加要随程序注册以运行的扩展名


  • 如果用户为您的应用程序运行卸载,此方法还有一个额外的好处,即在卸载后进行清理。

    如果您使用ClickOnce部署,这一切都将为您处理(至少在VS2008 SP1中);简单地说:

    • 项目属性
    • 发表
    • 选择权
    • 文件关联
    • (添加您需要的内容)
    (请注意,它必须是完全信任的,目标为.NET 3.5,并设置为脱机使用)

    有关“Windows注册表”方式的详细信息,请参见MSDN:

    我在HKEY\U CURRENT\U USER\Software\Classes下创建密钥(如Ishmael所说)

    并按照X-Cubed回答的说明进行操作

    示例代码如下所示:

    private void Create_abc_FileAssociation()
    {
        /***********************************/
        /**** Key1: Create ".abc" entry ****/
        /***********************************/
        Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);
    
        key1.CreateSubKey("Classes");
        key1 = key1.OpenSubKey("Classes", true);
    
        key1.CreateSubKey(".abc");
        key1 = key1.OpenSubKey(".abc", true);
        key1.SetValue("", "DemoKeyValue"); // Set default key value
    
        key1.Close();
    
        /*******************************************************/
        /**** Key2: Create "DemoKeyValue\DefaultIcon" entry ****/
        /*******************************************************/
        Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);
    
        key2.CreateSubKey("Classes");
        key2 = key2.OpenSubKey("Classes", true);
    
        key2.CreateSubKey("DemoKeyValue");
        key2 = key2.OpenSubKey("DemoKeyValue", true);
    
        key2.CreateSubKey("DefaultIcon");
        key2 = key2.OpenSubKey("DefaultIcon", true);
        key2.SetValue("", "\"" + "(The icon path you desire)" + "\""); // Set default key value
    
        key2.Close();
    
        /**************************************************************/
        /**** Key3: Create "DemoKeyValue\shell\open\command" entry ****/
        /**************************************************************/
        Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);
    
        key3.CreateSubKey("Classes");
        key3 = key3.OpenSubKey("Classes", true);
    
        key3.CreateSubKey("DemoKeyValue");
        key3 = key3.OpenSubKey("DemoKeyValue", true);
    
        key3.CreateSubKey("shell");
        key3 = key3.OpenSubKey("shell", true);
    
        key3.CreateSubKey("open");
        key3 = key3.OpenSubKey("open", true);
    
        key3.CreateSubKey("command");
        key3 = key3.OpenSubKey("command", true);
        key3.SetValue("", "\"" + "(The application path you desire)" + "\"" + " \"%1\""); // Set default key value
    
        key3.Close();
    }
    

    给你们看一个快速的演示,很容易理解。您可以修改这些关键值,一切都很好。

    下面是一个完整的示例:

    public class FileAssociation
    {
        public string Extension { get; set; }
        public string ProgId { get; set; }
        public string FileTypeDescription { get; set; }
        public string ExecutableFilePath { get; set; }
    }
    
    public class FileAssociations
    {
        // needed so that Explorer windows get refreshed after the registry is updated
        [System.Runtime.InteropServices.DllImport("Shell32.dll")]
        private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
    
        private const int SHCNE_ASSOCCHANGED = 0x8000000;
        private const int SHCNF_FLUSH = 0x1000;
    
        public static void EnsureAssociationsSet()
        {
            var filePath = Process.GetCurrentProcess().MainModule.FileName;
            EnsureAssociationsSet(
                new FileAssociation
                {
                    Extension = ".binlog",
                    ProgId = "MSBuildBinaryLog",
                    FileTypeDescription = "MSBuild Binary Log",
                    ExecutableFilePath = filePath
                },
                new FileAssociation
                {
                    Extension = ".buildlog",
                    ProgId = "MSBuildStructuredLog",
                    FileTypeDescription = "MSBuild Structured Log",
                    ExecutableFilePath = filePath
                });
        }
    
        public static void EnsureAssociationsSet(params FileAssociation[] associations)
        {
            bool madeChanges = false;
            foreach (var association in associations)
            {
                madeChanges |= SetAssociation(
                    association.Extension,
                    association.ProgId,
                    association.FileTypeDescription,
                    association.ExecutableFilePath);
            }
    
            if (madeChanges)
            {
                SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
            }
        }
    
        public static bool SetAssociation(string extension, string progId, string fileTypeDescription, string applicationFilePath)
        {
            bool madeChanges = false;
            madeChanges |= SetKeyDefaultValue(@"Software\Classes\" + extension, progId);
            madeChanges |= SetKeyDefaultValue(@"Software\Classes\" + progId, fileTypeDescription);
            madeChanges |= SetKeyDefaultValue($@"Software\Classes\{progId}\shell\open\command", "\"" + applicationFilePath + "\" \"%1\"");
            return madeChanges;
        }
    
        private static bool SetKeyDefaultValue(string keyPath, string value)
        {
            using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
            {
                if (key.GetValue(null) as string != value)
                {
                    key.SetValue(null, value);
                    return true;
                }
            }
    
            return false;
        }
    

    自从Windows7以来,有两个cmd工具,它们使得创建简单的文件关联变得非常容易。它们是和。下面是每个命令的基本解释

    • -将文件扩展名(如“.txt”)与“文件类型”关联
    • -定义用户打开给定“文件类型”时要运行的可执行文件
    请注意,这些是cmd工具,而不是可执行文件(exe)。这意味着它们只能在cmd窗口中运行,或者通过将ShellExecute与“cmd/c assoc”一起使用。您可以在链接中了解更多关于它们的信息,或者在cmd提示符下键入“assoc/?”和“ftype/?”

    因此,要将应用程序与.bob扩展名关联,可以打开一个cmd窗口(WindowKey+R,键入cmd,按enter键),然后运行以下操作:

    assoc .bob=BobFile
    ftype BobFile=c:\temp\BobView.exe "%1"
    
    这比搞乱注册表要简单得多,而且在未来的windows版本中更可能起作用

    最后,这里是一个C#函数,用于创建文件关联:

    public static int setFileAssociation(string[] extensions, string fileType, string openCommandString) {
        int v = execute("cmd", "/c ftype " + fileType + "=" + openCommandString);
        foreach (string ext in extensions) {
            v = execute("cmd", "/c assoc " + ext + "=" + fileType);
            if (v != 0) return v;
        }
        return v;
    }
    public static int execute(string exeFilename, string arguments) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = true;
        startInfo.FileName = exeFilename;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = arguments;
        try {
            using (Process exeProcess = Process.Start(startInfo)) {
                exeProcess.WaitForExit();
                return exeProcess.ExitCode;
            }
        } catch {
            return 1;
        }
    }
    

    下面的代码是一个应该可以工作的函数,它在windows注册表中添加了所需的值。通常我在可执行文件中运行SelfCreateAssociation(“.abc”)。(表单构造函数、onload或onshown)每次执行可执行文件时,它都会更新当前用户的注册表项。(如果您有一些更改,则适合调试)。 如果您需要有关所涉及注册表项的详细信息,请查看此MSDN链接

    要获取有关常规类的更多信息,请单击根注册表项。请参阅这篇MSDN文章

    public enum KeyHiveSmall
    {
    ClassesRoot,
    当前用户,
    本地机器,
    }
    /// 
    ///在windows注册表中为文件扩展名创建关联
    ///CreateAssociation(@“vendor.application”、“.tmf”、“工具文件”、@“C:\Windows\SYSWOW64\notepad.exe”、@“%SystemRoot%\SYS”
    
    public enum KeyHiveSmall
    {
        ClassesRoot,
        CurrentUser,
        LocalMachine,
    }
    
    /// <summary>
    /// Create an associaten for a file extension in the windows registry
    /// CreateAssociation(@"vendor.application",".tmf","Tool file",@"C:\Windows\SYSWOW64\notepad.exe",@"%SystemRoot%\SYSWOW64\notepad.exe,0");
    /// </summary>
    /// <param name="ProgID">e.g. vendor.application</param>
    /// <param name="extension">e.g. .tmf</param>
    /// <param name="description">e.g. Tool file</param>
    /// <param name="application">e.g.  @"C:\Windows\SYSWOW64\notepad.exe"</param>
    /// <param name="icon">@"%SystemRoot%\SYSWOW64\notepad.exe,0"</param>
    /// <param name="hive">e.g. The user-specific settings have priority over the computer settings. KeyHive.LocalMachine  need admin rights</param>
    public static void CreateAssociation(string ProgID, string extension, string description, string application, string icon, KeyHiveSmall hive = KeyHiveSmall.CurrentUser)
    {
        RegistryKey selectedKey = null;
    
        switch (hive)
        {
            case KeyHiveSmall.ClassesRoot:
                Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension).SetValue("", ProgID);
                selectedKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProgID);
                break;
    
            case KeyHiveSmall.CurrentUser:
                Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Classes\" + extension).SetValue("", ProgID);
                selectedKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Classes\" + ProgID);
                break;
    
            case KeyHiveSmall.LocalMachine:
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\Classes\" + extension).SetValue("", ProgID);
                selectedKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\Classes\" + ProgID);
                break;
        }
    
        if (selectedKey != null)
        {
            if (description != null)
            {
                selectedKey.SetValue("", description);
            }
            if (icon != null)
            {
                selectedKey.CreateSubKey("DefaultIcon").SetValue("", icon, RegistryValueKind.ExpandString);
                selectedKey.CreateSubKey(@"Shell\Open").SetValue("icon", icon, RegistryValueKind.ExpandString);
            }
            if (application != null)
            {
                selectedKey.CreateSubKey(@"Shell\Open\command").SetValue("", "\"" + application + "\"" + " \"%1\"", RegistryValueKind.ExpandString);
            }
        }
        selectedKey.Flush();
        selectedKey.Close();
    }
    
     /// <summary>
        /// Creates a association for current running executable
        /// </summary>
        /// <param name="extension">e.g. .tmf</param>
        /// <param name="hive">e.g. KeyHive.LocalMachine need admin rights</param>
        /// <param name="description">e.g. Tool file. Displayed in explorer</param>
        public static void SelfCreateAssociation(string extension, KeyHiveSmall hive = KeyHiveSmall.CurrentUser, string description = "")
        {
            string ProgID = System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.FullName;
            string FileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
            CreateAssociation(ProgID, extension, description, FileLocation, FileLocation + ",0", hive);
        }