繁体   English   中英

C# 在上下文菜单上以编程方式“打开”文件

[英]C# Programmatically “Open” on Context Menu a file

如何使用 C# 打开文件? 这次,我想在 c# 中模拟以下方式。

我想通过 c# 代码来实现并尽量避免以下情况。

Process.Start("sample.dot") 

然后结果是

在此处输入图像描述

这应该是 sample.dot 文件。

有趣的是,当我像下面这样打开时

在此处输入图像描述

文件名出现了我想要的并且可以保存。

在此处输入图像描述

我唯一能得到解决方案的就是为整个文件扩展名寻找 HKEY_CLASS_ROOT 注册表。 然后获取exe命令并以完全相同的方式运行。

但我认为有更有效的解决方案。

在此处输入图像描述

是否可以通过 C# 代码模拟“打开”?

如果您能帮助我,那就太好了,谢谢!

Windows 注册表编辑器版本 5.00

[HKEY_CLASSES_ROOT*\shell\使用 MyThing 打开] "Icon"="C:\foo\myThing.exe"

[HKEY_CLASSES_ROOT*\shell\使用 MyThing\command 打开] @="C:\foo\myThing.exe \"%1\""

您在该上下文菜单中看到的内容是注册表中文件关联数据的一部分。

回到过去,界面对此更加清晰:

在此处输入图像描述

资料来源: https://techjourney.net/windows-file-types-open-edit-actions-associations-advanced-management-tools/

这些关联可以通过文件扩展名或协议来完成(如 http:)。 有时甚至两者分开。

大多数指南都是关于为此使用 Regedit:

但是 .NET 是 class : https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registry.setvalue

感谢你们对我的帮助。

我终于通过从注册表键中寻找“打开”菜单命令来解决。

这是要寻找的代码。

shellComand 需要:新建、打开、编辑。 下面的代码寻找打开菜单上下文命令。

static string SeekExtensionBehaviour(string path, string shellComand)
{            
    string extension = System.IO.Path.GetExtension(path);

    string command = "not found";

    if (string.IsNullOrWhiteSpace(extension)) return command;

    using (RegistryKey keyExt = Registry.ClassesRoot.OpenSubKey(extension))
    {
        if (keyExt == null) return command;

        var keyRealExt = keyExt.GetValue("");

        if (string.IsNullOrEmpty(keyRealExt.ToString())) return command;

        using (RegistryKey keyReal = Registry.ClassesRoot.OpenSubKey(keyRealExt.ToString()))
        {
            if (keyReal == null) return command;

            string keycommandPath = string.Format(@"shell\{0}\command", shellComand); // New, Open or Edit

            using (RegistryKey keyCommand = keyReal.OpenSubKey(keycommandPath))
            {
                command = keyCommand.GetValue("").ToString();
            }
        }
    }

    return command; // "C:\Program Files (x86)\Microsoft Office\Root\Office16\WINWORD.EXE" /n "%1" /o "%u"
}

string command = SeekExtensionBehaviour("override shell command.dot", "Open");

请替换 'command' 参数的变量,因为它有 %1 和 %u。 %1 是打开文件的路径。

非常感谢你们!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM