c# 从上下文菜单 Windows 资源管理器中选择的 file/folder 检索 file/folder 路径

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

我正在尝试在 Windows 资源管理器的上下文菜单中为任何文件和文件夹实现一个选项。 我通过写入 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();

应用程序按我的意愿打开,但是我不知道如何获取在上下文菜单中选择的 file/folder 的路径。我该怎么做?

将注册表项的值更改为

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

因此 %1 被替换为选定的 file/folder。在您的主要方法中,您可以通过以下方式访问它:

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

不幸的是,这不适用于多选。放置 %2 等是没有用的。如果选择了多个文件或文件夹,您的应用程序将分别为每个文件或文件夹调用。

René Vogt 的回答只有这一行很棒:

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

应该是:

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

当目录或文件路径包含空格时,args[] 数组包含多个字符串,但没有引号。