<p>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 the given file as the first argument.
Ideally it'd also set the icon for the given file extensions to the icon for my executable.
Thanks all.</p>

[{'answer_id': 69805, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 2, 'selected': False, 'text': '<p>The file associations are defined in the registry under HKEY_CLASSES_ROOT.</p>\n\n<p>There\'s a VB.NET example <a href="http://www.devx.com/vb2themax/Tip/19554?type=kbArticle&amp;trk=MSCP" rel="nofollow noreferrer">here</a> that I\'m you can port easily to C#.</p>\n'}, {'answer_id': 69826, 'author': 'X-Cubed', 'author_id': 10808, 'author_profile': 'https://Stackoverflow.com/users/10808', 'pm_score': 5, 'selected': False, 'text': '<p>There doesn\'t appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to.</p>\n\n<p>You\'ll need to create a key under HKEY_CLASSES_ROOT with the name set to your file extension (eg: ".txt"). Set the default value of this key to a unique name for your file type, such as "Acme.TextFile". Then create another key under HKEY_CLASSES_ROOT with the name set to "Acme.TextFile". Add a subkey called "DefaultIcon" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called "shell". Under the "shell" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and "%1" to represent the path to the file selected.</p>\n\n<p>For instance, here\'s a sample registry file to create an association between .txt files and EmEditor:</p>\n\n<pre>\nWindows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\.txt]\n@="emeditor.txt"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt]\n@="Text Document"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\DefaultIcon]\n@="%SystemRoot%\\\\SysWow64\\\\imageres.dll,-102"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\open]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\open\\command]\n@="\\"C:\\\\Program Files\\\\EmEditor\\\\EMEDITOR.EXE\\" \\"%1\\""\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\print]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\print\\command]\n@="\\"C:\\\\Program Files\\\\EmEditor\\\\EMEDITOR.EXE\\" /p \\"%1\\""\n</pre>\n'}, {'answer_id': 69863, 'author': 'Ishmaeel', 'author_id': 227, 'author_profile': 'https://Stackoverflow.com/users/227', 'pm_score': 5, 'selected': False, 'text': "<p>Also, if you decide to go the registry way, keep in mind that current user associations are under <strong>HKEY_CURRENT_USER\\Software\\Classes</strong>. It might be better to add your application there instead of local machine classes.</p>\n\n<p>If your program will be run by limited users, you won't be able to modify CLASSES_ROOT anyway.</p>\n"}, {'answer_id': 899360, 'author': 'Paul J', 'author_id': 111237, 'author_profile': 'https://Stackoverflow.com/users/111237', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<p>Here's how to create file extension association using the built-in Visual Studio Install tools:</p>\n\n<ol>\n<li><p>Within your existing C# solution, add a new project and select project type as <code>Other Project Types</code> -> <code>Setup and Deployment</code> -> <code>Setup Project</code> (or try the Setup Wizard)</p></li>\n<li><p>Configure your installer (plenty of existing docs for this if you need help)</p></li>\n<li><p>Right-click the setup project in the Solution explorer, select <code>View</code> -> <code>File Types</code>, and then add the extension that you want to register along with the program to run it.</p></li>\n</ol>\n\n<p>This method has the added benefit of cleaning up after itself if a user runs the uninstall for your application.</p>\n"}, {'answer_id': 1327322, 'author': 'Marc Gravell', 'author_id': 23354, 'author_profile': 'https://Stackoverflow.com/users/23354', 'pm_score': 4, 'selected': False, 'text': '<p>If you use ClickOnce deployment, this is all handled for you (at least, in VS2008 SP1); simply:</p>\n\n<ul>\n<li>Project Properties</li>\n<li>Publish</li>\n<li>Options</li>\n<li>File Associatons</li>\n<li>(add whatever you need)</li>\n</ul>\n\n<p>(note that it must be full-trust, target .NET 3.5, and be set for offline usage)</p>\n\n<p>See also MSDN: <a href="http://msdn.microsoft.com/en-us/library/bb892924.aspx" rel="noreferrer">How to: Create File Associations For a ClickOnce Application</a></p>\n'}, {'answer_id': 28585998, 'author': 'Strong84', 'author_id': 1422691, 'author_profile': 'https://Stackoverflow.com/users/1422691', 'pm_score': 3, 'selected': False, 'text': '<p>To be specific about the "Windows Registry" way:</p>\n\n<p>I create keys under <strong>HKEY_CURRENT_USER\\Software\\Classes</strong> (like Ishmaeel said)</p>\n\n<p>and follow the instruction answered by X-Cubed.</p>\n\n<p>The sample code looks like:</p>\n\n<pre><code>private void Create_abc_FileAssociation()\n{\n    /***********************************/\n    /**** Key1: Create ".abc" entry ****/\n    /***********************************/\n    Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);\n\n    key1.CreateSubKey("Classes");\n    key1 = key1.OpenSubKey("Classes", true);\n\n    key1.CreateSubKey(".abc");\n    key1 = key1.OpenSubKey(".abc", true);\n    key1.SetValue("", "DemoKeyValue"); // Set default key value\n\n    key1.Close();\n\n    /*******************************************************/\n    /**** Key2: Create "DemoKeyValue\\DefaultIcon" entry ****/\n    /*******************************************************/\n    Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);\n\n    key2.CreateSubKey("Classes");\n    key2 = key2.OpenSubKey("Classes", true);\n\n    key2.CreateSubKey("DemoKeyValue");\n    key2 = key2.OpenSubKey("DemoKeyValue", true);\n\n    key2.CreateSubKey("DefaultIcon");\n    key2 = key2.OpenSubKey("DefaultIcon", true);\n    key2.SetValue("", "\\"" + "(The icon path you desire)" + "\\""); // Set default key value\n\n    key2.Close();\n\n    /**************************************************************/\n    /**** Key3: Create "DemoKeyValue\\shell\\open\\command" entry ****/\n    /**************************************************************/\n    Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);\n\n    key3.CreateSubKey("Classes");\n    key3 = key3.OpenSubKey("Classes", true);\n\n    key3.CreateSubKey("DemoKeyValue");\n    key3 = key3.OpenSubKey("DemoKeyValue", true);\n\n    key3.CreateSubKey("shell");\n    key3 = key3.OpenSubKey("shell", true);\n\n    key3.CreateSubKey("open");\n    key3 = key3.OpenSubKey("open", true);\n\n    key3.CreateSubKey("command");\n    key3 = key3.OpenSubKey("command", true);\n    key3.SetValue("", "\\"" + "(The application path you desire)" + "\\"" + " \\"%1\\""); // Set default key value\n\n    key3.Close();\n}\n</code></pre>\n\n<p>Just show you guys a quick demo, very easy to understand. You could modify those key values and everything is good to go.</p>\n'}, {'answer_id': 44816888, 'author': 'Kirill Osenkov', 'author_id': 37899, 'author_profile': 'https://Stackoverflow.com/users/37899', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a complete example:</p>\n\n<pre><code>public class FileAssociation\n{\n    public string Extension { get; set; }\n    public string ProgId { get; set; }\n    public string FileTypeDescription { get; set; }\n    public string ExecutableFilePath { get; set; }\n}\n\npublic class FileAssociations\n{\n    // needed so that Explorer windows get refreshed after the registry is updated\n    [System.Runtime.InteropServices.DllImport("Shell32.dll")]\n    private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);\n\n    private const int SHCNE_ASSOCCHANGED = 0x8000000;\n    private const int SHCNF_FLUSH = 0x1000;\n\n    public static void EnsureAssociationsSet()\n    {\n        var filePath = Process.GetCurrentProcess().MainModule.FileName;\n        EnsureAssociationsSet(\n            new FileAssociation\n            {\n                Extension = ".binlog",\n                ProgId = "MSBuildBinaryLog",\n                FileTypeDescription = "MSBuild Binary Log",\n                ExecutableFilePath = filePath\n            },\n            new FileAssociation\n            {\n                Extension = ".buildlog",\n                ProgId = "MSBuildStructuredLog",\n                FileTypeDescription = "MSBuild Structured Log",\n                ExecutableFilePath = filePath\n            });\n    }\n\n    public static void EnsureAssociationsSet(params FileAssociation[] associations)\n    {\n        bool madeChanges = false;\n        foreach (var association in associations)\n        {\n            madeChanges |= SetAssociation(\n                association.Extension,\n                association.ProgId,\n                association.FileTypeDescription,\n                association.ExecutableFilePath);\n        }\n\n        if (madeChanges)\n        {\n            SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);\n        }\n    }\n\n    public static bool SetAssociation(string extension, string progId, string fileTypeDescription, string applicationFilePath)\n    {\n        bool madeChanges = false;\n        madeChanges |= SetKeyDefaultValue(@"Software\\Classes\\" + extension, progId);\n        madeChanges |= SetKeyDefaultValue(@"Software\\Classes\\" + progId, fileTypeDescription);\n        madeChanges |= SetKeyDefaultValue($@"Software\\Classes\\{progId}\\shell\\open\\command", "\\"" + applicationFilePath + "\\" \\"%1\\"");\n        return madeChanges;\n    }\n\n    private static bool SetKeyDefaultValue(string keyPath, string value)\n    {\n        using (var key = Registry.CurrentUser.CreateSubKey(keyPath))\n        {\n            if (key.GetValue(null) as string != value)\n            {\n                key.SetValue(null, value);\n                return true;\n            }\n        }\n\n        return false;\n    }\n</code></pre>\n'}, {'answer_id': 46900103, 'author': 'Mike', 'author_id': 1943229, 'author_profile': 'https://Stackoverflow.com/users/1943229', 'pm_score': 0, 'selected': False, 'text': '<p>There are two cmd tools that have been around since Windows 7 which make it very easy to create simple file associations. They are <a href="https://technet.microsoft.com/en-us/library/cc770920(v=ws.11).aspx" rel="nofollow noreferrer">assoc</a> and <a href="https://technet.microsoft.com/en-us/library/cc771394(v=ws.11).aspx" rel="nofollow noreferrer">ftype</a>. Here\'s a basic explanation of each command.</p>\n\n<ul>\n<li><a href="https://technet.microsoft.com/en-us/library/cc770920(v=ws.11).aspx" rel="nofollow noreferrer">Assoc</a> - associates a file extension (like \'.txt\') with a "file type."</li>\n<li><a href="https://technet.microsoft.com/en-us/library/cc771394(v=ws.11).aspx" rel="nofollow noreferrer">FType</a> - defines an executable to run when the user opens a given "file type."</li>\n</ul>\n\n<p>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. </p>\n\n<p>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:</p>\n\n<pre><code>assoc .bob=BobFile\nftype BobFile=c:\\temp\\BobView.exe "%1"\n</code></pre>\n\n<p>This is much simpler than messing with the registry and it is more likely to work in future windows version. </p>\n\n<p>Wrapping it up, here is a C# function to create a file association:</p>\n\n<pre><code>public static int setFileAssociation(string[] extensions, string fileType, string openCommandString) {\n    int v = execute("cmd", "/c ftype " + fileType + "=" + openCommandString);\n    foreach (string ext in extensions) {\n        v = execute("cmd", "/c assoc " + ext + "=" + fileType);\n        if (v != 0) return v;\n    }\n    return v;\n}\npublic static int execute(string exeFilename, string arguments) {\n    ProcessStartInfo startInfo = new ProcessStartInfo();\n    startInfo.CreateNoWindow = false;\n    startInfo.UseShellExecute = true;\n    startInfo.FileName = exeFilename;\n    startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n    startInfo.Arguments = arguments;\n    try {\n        using (Process exeProcess = Process.Start(startInfo)) {\n            exeProcess.WaitForExit();\n            return exeProcess.ExitCode;\n        }\n    } catch {\n        return 1;\n    }\n}\n</code></pre>\n'}, {'answer_id': 46902772, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>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).\nIf you need detailed information about the registry keys involved check out this MSDN link.</p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx</a> </p>\n\n<p>To get more information about the general ClassesRoot registry key. See this MSDN article.</p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx</a></p>\n\n<pre><code>public enum KeyHiveSmall\n{\n    ClassesRoot,\n    CurrentUser,\n    LocalMachine,\n}\n\n/// &lt;summary&gt;\n/// Create an associaten for a file extension in the windows registry\n/// CreateAssociation(@"vendor.application",".tmf","Tool file",@"C:\\Windows\\SYSWOW64\\notepad.exe",@"%SystemRoot%\\SYSWOW64\\notepad.exe,0");\n/// &lt;/summary&gt;\n/// &lt;param name="ProgID"&gt;e.g. vendor.application&lt;/param&gt;\n/// &lt;param name="extension"&gt;e.g. .tmf&lt;/param&gt;\n/// &lt;param name="description"&gt;e.g. Tool file&lt;/param&gt;\n/// &lt;param name="application"&gt;e.g.  @"C:\\Windows\\SYSWOW64\\notepad.exe"&lt;/param&gt;\n/// &lt;param name="icon"&gt;@"%SystemRoot%\\SYSWOW64\\notepad.exe,0"&lt;/param&gt;\n/// &lt;param name="hive"&gt;e.g. The user-specific settings have priority over the computer settings. KeyHive.LocalMachine  need admin rights&lt;/param&gt;\npublic static void CreateAssociation(string ProgID, string extension, string description, string application, string icon, KeyHiveSmall hive = KeyHiveSmall.CurrentUser)\n{\n    RegistryKey selectedKey = null;\n\n    switch (hive)\n    {\n        case KeyHiveSmall.ClassesRoot:\n            Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension).SetValue("", ProgID);\n            selectedKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProgID);\n            break;\n\n        case KeyHiveSmall.CurrentUser:\n            Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\\Classes\\" + extension).SetValue("", ProgID);\n            selectedKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\\Classes\\" + ProgID);\n            break;\n\n        case KeyHiveSmall.LocalMachine:\n            Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\\Classes\\" + extension).SetValue("", ProgID);\n            selectedKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\\Classes\\" + ProgID);\n            break;\n    }\n\n    if (selectedKey != null)\n    {\n        if (description != null)\n        {\n            selectedKey.SetValue("", description);\n        }\n        if (icon != null)\n        {\n            selectedKey.CreateSubKey("DefaultIcon").SetValue("", icon, RegistryValueKind.ExpandString);\n            selectedKey.CreateSubKey(@"Shell\\Open").SetValue("icon", icon, RegistryValueKind.ExpandString);\n        }\n        if (application != null)\n        {\n            selectedKey.CreateSubKey(@"Shell\\Open\\command").SetValue("", "\\"" + application + "\\"" + " \\"%1\\"", RegistryValueKind.ExpandString);\n        }\n    }\n    selectedKey.Flush();\n    selectedKey.Close();\n}\n\n /// &lt;summary&gt;\n    /// Creates a association for current running executable\n    /// &lt;/summary&gt;\n    /// &lt;param name="extension"&gt;e.g. .tmf&lt;/param&gt;\n    /// &lt;param name="hive"&gt;e.g. KeyHive.LocalMachine need admin rights&lt;/param&gt;\n    /// &lt;param name="description"&gt;e.g. Tool file. Displayed in explorer&lt;/param&gt;\n    public static void SelfCreateAssociation(string extension, KeyHiveSmall hive = KeyHiveSmall.CurrentUser, string description = "")\n    {\n        string ProgID = System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.FullName;\n        string FileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;\n        CreateAssociation(ProgID, extension, description, FileLocation, FileLocation + ",0", hive);\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/69761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']