【问题标题】:Use Process.Start with parameters AND spaces in path使用 Process.Start,路径中带有参数和空格
【发布时间】:2013-06-23 15:56:22
【问题描述】:

我见过类似的例子,但找不到与我的问题完全一样的东西。

我需要从 C# 运行这样的命令:

C:\FOLDER\folder with spaces\OTHER_FOLDER\executable.exe p1=hardCodedv1 p2=v2

我在运行时设置 v2,所以我需要能够在调用 Process.Start 之前修改 C# 中的字符串。有谁知道如何处理这个问题,因为我的参数之间有空格?

【问题讨论】:

  • 传递给 ProcessStartInfo.Filename 或 Process.Start(string, string) 的路径中的空格不是问题。它只是一个解析可能被它混淆的字符串的程序,比如 cmd.exe
  • @HansPassant vlc.exe 也被文件名中的空格弄糊涂了。所以我必须使用史蒂夫的建议让 Procees.Start 为我工作。

标签: c# process.start


【解决方案1】:

试试这个

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName =  "\"C:\\FOLDER\\folder with   spaces\\OTHER_FOLDER\\executable.exe\"";
startInfo.Arguments = "p1=hardCodedv1 p2=v2";
Process.Start(startInfo);

【讨论】:

  • 这是完美的,除了没有 startInfo.Start() 方法。我不得不像@Steve 建议的那样使用 Process.Start(startInfo) 。不过感谢您的帮助。
【解决方案2】:

您可以使用ProcessStartInfo 类来分隔您的参数、文件名、工作目录和参数,而无需担心空格

string fullPath = @"C:\FOLDER\folder with spaces\OTHER_FOLDER\executable.exe"
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = Path.GetFileName(fullPath);
psi.WorkingDirectory = Path.GetDirectoryName(fullPath);
psi.Arguments = "p1=hardCodedv1 p2=" + MakeParameter();
Process.Start(psi);

其中 MakeParameter 是一个函数,它返回要用于 p2 参数的字符串

【讨论】:

    【解决方案3】:

    即使您使用 ProcessStartInfo 类,如果您必须为参数添加空格,那么上述答案也无法解决问题。有一个简单的解决方案。只需在参数周围添加引号。就是这样。

     string fileName = @"D:\Company Accounts\Auditing Sep-2014 Reports.xlsx";
     System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
     startInfo.FileName = "Excel.exe";
     startInfo.Arguments = "\"" + fileName + "\"";
     System.Diagnostics.Process.Start(startInfo);
    

    这里我在文件名周围添加了转义引号,它可以工作。

    【讨论】:

    • 这也可以在一行中用 Process.Start("Excel.exe", "\"" + fileName + "\"");
    • 是的,但在这里我试图突出添加引号以避免初学者混淆
    【解决方案4】:

    在查看了提供的其他解决方案后,我遇到了一个问题,即我所有的各种参数都被捆绑到一个参数中。

    "-setting0=arg0 --subsetting0=arg1"

    所以我会提出以下建议:

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "\"" + Prefs.CaptureLocation.FullName + "\"";
            psi.Arguments = String.Format("-setting0={0} --subsetting0={1}", "\"" + arg0 + "\"", "\"" + arg1+ "\"");
            Process.Start(psi);
    

    在每个参数周围加上引号,而不是在整个参数集周围。正如Red_Shadow 所指出的,这一切都可以用单行来完成

            Process.Start("\"" + filename + "\"", arguments here)
    

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      相关资源
      最近更新 更多