【问题标题】:How to execute a ready-made Windows Run command如何执行现成的 Windows Run 命令
【发布时间】:2019-08-21 18:46:36
【问题描述】:

我需要使用从 Windows 注册表接收到的命令行启动默认邮件客户端。如何在 C# 中做到这一点? Process.Start 无法执行整行,需要拆分,但不知道会是什么

例如,我在注册表中运行一行

HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail\Microsoft Outlook\shell\open\command

如何用 c# 运行这个命令行?

"C:\PROGRA~2\MICROS~1\Office16\OUTLOOK.EXE" /recycle

更复杂的例子

%systemRoot%\system32\rundll32.exe "%ProgramFiles%\Internet Explorer\hmmapi.dll",OpenInboxHandler

【问题讨论】:

  • "" 之间的内容作为进程,其余的作为命令行参数。
  • 或许还有更优雅的方式
  • 谢谢,问题已解决,缺少 /C 选项

标签: c# winforms shell process.start


【解决方案1】:

这样做了

string[] lines = cmd.Split('"');
if (lines.Length > 1)
{
    ProcessStartInfo process = new ProcessStartInfo(lines[1].Trim());
    process.UseShellExecute = true;
    if (lines.Length > 2)
        process.Arguments = lines[2].Trim();
    Process.Start(process);
}

但不要吃它

%systemRoot%\system32\rundll32.exe "%ProgramFiles%\Internet Explorer\hmmapi.dll",OpenInboxHandler

【讨论】:

  • 如果命令行参数中有引号,这将不起作用。它适用于您找到的 Outlook 命令行,但您不能确定其他一些已设置为默认值的客户端在参数中没有引号。 Reza Aghaei 建议的是一种更稳健的方法。
  • ^更不用说这也会抓住双引号之间的内容 (") ,所以 lines[2].Trim() 很可能是 string.Empty
【解决方案2】:

问题已解决! 执行任意shell命令,需要为cmd.exe指定/C参数

public static void ExecuteShellCommand(string command)
{
    var ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
    {
        WindowStyle = ProcessWindowStyle.Hidden,
        CreateNoWindow = true,
        UseShellExecute = true
    };
    Process.Start(ProcessInfo);
}

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2021-09-08
    • 2021-11-14
    相关资源
    最近更新 更多