Search code examples
c#clickonceargsfile-association

Associated extension doesn't send file name to application on double click


I have specified a file extension to be associated with my program (Window Application) through Project Properties >> Publish >> Options >> File Associations in Visual Studio 2013.

I know that if I drag one or several files and drop it on my application (.exe), I can catch all the paths through the arguments (string[] args) of my Main method (located in Program.cs). But when I open an associated file (which launches my published and installed application), the path of the file is not passed as an argument to my Main method.

How can I catch the path of the file(s) which has launched my application?

BTW, I can also use registry (HKEY_CLASSES_ROOT) to associate file extensions with my application beside using Visual Studio's "File Associations" feature. Which method do you recommend the most and why?


Solution

  • I actually solved my own problem with the following code:

            RegistryKey command, defaultIcon, extension;
            // Create Keys
            command = Registry.CurrentUser.CreateSubKey(@"Software\Classes\APP NAME\shell\open\command");
            defaultIcon = Registry.CurrentUser.CreateSubKey(@"Software\Classes\APP NAME\DefaultIcon");
            extension = Registry.CurrentUser.CreateSubKey(@"Software\Classes\.EXTENSION");
    
            // Create Values
            command.SetValue("", "\"" + Application.ExecutablePath + "\" %1", RegistryValueKind.String);
            defaultIcon.SetValue("", "ICON PATH", RegistryValueKind.String);
            extension.SetValue("", "APP NAME", RegistryValueKind.String);
    

    APP NAME is where I put the name of my application, EXTENSION is where I put the extension I want to associate with my application, and ICON PATH is the path to the icon file which I want the associated files to have.

    The %1 at the end of the ExecutablePath makes the path of the double-clicked associated file to be passed as an argument to Main method of my application.