Search code examples
c#windowsshellcontextmenuwindows-explorer

c# retrieve file/folder path from selected file/folder in Context Menu Windows Explorer


I'm trying to implement an option in the context menu of Windows Explorer for any file and any folder. I have accomplish this by writing into regedit.

Using Microsoft.Win32;
...
RegistryKey key;
// Register to any file
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CLASSES\*\shell\MyProject");
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CLASSES\*\shell\MyProject\command");
// Register to folder
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CLASSES\Folder\shell\MyProject");
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CLASSES\Folder\shell\MyProject\command");
// Default value points to the app
key.SetValue("", Application.StartupPath + @"\MyProject.exe");
key.Close();

The application opens as I want, however I have no clue how to grab the path of file/folder that was selected in the context menu. How can I do this?


Solution

  • Change the value of the registry key to

    key.SetValue("", Application.StartupPath + @"\MyProject.exe %1");
    

    So %1 is replaced with the selected file/folder. In your main method you can access this via:

    static void Main(string[] args)
    {
        Console.WriteLine("Selected file/folder: {0}", args[0]);
    }
    

    Unfortunatly this will not work for multi-selection. Placing %2 etc is of no use. If multiple files or folders are selected your application gets called for each of them seperatly.