How to associate a file extension to the current executable in C#

后端 未结 9 2145
故里飘歌
故里飘歌 2020-11-22 12:01

I\'d like to to associate a file extension to the current executable in C#. This way when the user clicks on the file afterwards in explorer, it\'ll run my executable with t

相关标签:
9条回答
  • 2020-11-22 12:45

    There may be specific reasons why you choose not to use an install package for your project but an install package is a great place to easily perform application configuration tasks such registering file extensions, adding desktop shortcuts, etc.

    Here's how to create file extension association using the built-in Visual Studio Install tools:

    1. Within your existing C# solution, add a new project and select project type as Other Project Types -> Setup and Deployment -> Setup Project (or try the Setup Wizard)

    2. Configure your installer (plenty of existing docs for this if you need help)

    3. Right-click the setup project in the Solution explorer, select View -> File Types, and then add the extension that you want to register along with the program to run it.

    This method has the added benefit of cleaning up after itself if a user runs the uninstall for your application.

    0 讨论(0)
  • 2020-11-22 12:46

    The file associations are defined in the registry under HKEY_CLASSES_ROOT.

    There's a VB.NET example here that I'm you can port easily to C#.

    0 讨论(0)
  • 2020-11-22 12:52

    The code below is a function the should work, it adds the required values in the windows registry. Usually i run SelfCreateAssociation(".abc") in my executable. (form constructor or onload or onshown) It will update the registy entry for the current user, everytime the executable is executed. (good for debugging, if you have some changes). If you need detailed information about the registry keys involved check out this MSDN link.

    https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx

    To get more information about the general ClassesRoot registry key. See this MSDN article.

    https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx

    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);
        }
    
    0 讨论(0)
  • 2020-11-22 12:57

    If you use ClickOnce deployment, this is all handled for you (at least, in VS2008 SP1); simply:

    • Project Properties
    • Publish
    • Options
    • File Associatons
    • (add whatever you need)

    (note that it must be full-trust, target .NET 3.5, and be set for offline usage)

    See also MSDN: How to: Create File Associations For a ClickOnce Application

    0 讨论(0)
  • 2020-11-22 12:58

    There are two cmd tools that have been around since Windows 7 which make it very easy to create simple file associations. They are assoc and ftype. Here's a basic explanation of each command.

    • Assoc - associates a file extension (like '.txt') with a "file type."
    • FType - defines an executable to run when the user opens a given "file type."

    Note that these are cmd tools and not executable files (exe). This means that they can only be run in a cmd window, or by using ShellExecute with "cmd /c assoc." You can learn more about them at the links or by typing "assoc /?" and "ftype /?" at a cmd prompt.

    So to associate an application with a .bob extension, you could open a cmd window (WindowKey+R, type cmd, press enter) and run the following:

    assoc .bob=BobFile
    ftype BobFile=c:\temp\BobView.exe "%1"
    

    This is much simpler than messing with the registry and it is more likely to work in future windows version.

    Wrapping it up, here is a C# function to create a file association:

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:00

    To be specific about the "Windows Registry" way:

    I create keys under HKEY_CURRENT_USER\Software\Classes (like Ishmaeel said)

    and follow the instruction answered by X-Cubed.

    The sample code looks like:

    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();
    }
    

    Just show you guys a quick demo, very easy to understand. You could modify those key values and everything is good to go.

    0 讨论(0)
提交回复
热议问题