使用进程.从参数和路径中的空格开始



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

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

C:FOLDERfolder with spacesOTHER_FOLDERexecutable.exe p1=hardCodedv1 p2=v2

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

即使在使用ProcessStartInfo类时,如果必须为参数添加空格,那么以上答案也无法解决问题。有一个简单的解决方案。只需在参数周围加引号即可。仅此而已。

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

在这里,我在文件名周围添加了转义引号,它很有效。

您可以使用ProcessStartInfo类来分离您的参数、FileName、WorkingDirectory和参数,而无需担心空间

string fullPath = @"C:FOLDERfolder with spacesOTHER_FOLDERexecutable.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参数的字符串

试试这个

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);

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

"-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)

非常微妙的警告:
如果我使用ArgumentList,它只有在使用严格修剪(没有前导或尾随空格)并且每个字符串都位于自己的数组位置时才有效。

    var psi = new ProcessStartInfo("cmd") {
        ArgumentList = {
            "--somepath",
            "/root/subpath",
            "--someid",
            "12345",
        }
    };

例如,如果我尝试

 "--somepath /root/subpath",

它不起作用,并且我从cmd应用程序中得到错误。

甚至

        "--somepath ",

中断接收程序的解析器。

如果要启动的进程是cmd/C
并且参数包含多个空格,如
C:\Program Files(x86)\Adobe\Arobat-Reader DC\Reader\AcroRd32.exe/N/T C:\users\someuser\AppData\Local\Temp\Temp file with spaces.tmp Printer Name with spaces
也许这个答案会对您有所帮助:

https://stackoverflow.com/a/6378038/20704455

简而言之:双引号

 string arguments ="/C ""C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" /N /T "C:\users\someuser\AppData\Local\Temp\temp file with spaces.tmp" "Printer Name with Spaces""";
 ProcessStartInfo procStartInfo = new ProcessStartInfo("C:\Windows\sysnative\cmd.exe",arguments);

最新更新