Linesofcode
Linesofcode

Reputation: 5903

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?

Upvotes: 2

Views: 2355

Answers (2)

Michael Trapp
Michael Trapp

Reputation: 141

The answer of René Vogt is great only this line:

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

should be:

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

Without the quotation marks the args[] array contains multiple strings when the directory or file path contains whitespaces.

Upvotes: 1

René Vogt
René Vogt

Reputation: 43946

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.

Upvotes: 1

Related Questions