C#在Windows 8上使用路径中的空格执行外部进程

时间:2012-12-29 14:17:34

标签: c#

当在Windows 8上的路径中有空格时,我在使用C#启动进程时遇到问题,即使路径是双引号也是如此!

以下代码在我们的XP和Windows 7计算机上运行良好多年,但我们最近将一些开发框切换到Windows 8,现在我们收到以下错误:

'D:\Workspace\Visual' is not recognized as an internal or external command, operable program or batch file.

代码:

string command = "\"D:\\Workspace\\Visual Studio 2010\\Dev\\Tools\\Editors\\AssetManager\\bin\\Tools\\TextureAtlasBuilder.exe\"";
string arguments = "\"D:\\Local\\Temp\\xu2twc4d.cg1\" \"environment-textures\"";

ProcessStartInfo startInfo = new ProcessStartInfo
{
    CreateNoWindow = true,
    UseShellExecute = false,
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    FileName = string.Format(CultureInfo.InvariantCulture, @"{0}\cmd.exe", Environment.SystemDirectory),
    Arguments = string.Format(CultureInfo.InvariantCulture, "/C {0} {1}", command, arguments)
};

Process process = new Process
{
    StartInfo = startInfo
};

process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(StandardErrorHandler);

process.Start();

我尝试过带有和不带双引号的文字字符串,带有和不带双引号的逐字字符串,我总是得到同样的错误!

我做错了什么?!

由于

2 个答案:

答案 0 :(得分:1)

从你的参数字符串中删除“。

这很棘手,因为/ C的cmd行为对使用“非常严格”,因为可以从cmd /?中找到。如果全部失败:将命令行和参数写入临时cmd文件并启动它...

  

如果指定了/ C或/ K,那么后面的命令行的其余部分   交换机作为命令行处理,其中包含以下逻辑   用于处理引号(“)字符:

1.  If all of the following conditions are met, then quote characters
    on the command line are preserved:

    - no /S switch
    - exactly two quote characters
    - no special characters between the two quote characters,
      where special is one of: &<>()@^|
    - there are one or more whitespace characters between the
      two quote characters
    - the string between the two quote characters is the name
      of an executable file.

2.  Otherwise, old behavior is to see if the first character is
    a quote character and if so, strip the leading character and
    remove the last quote character on the command line, preserving
    any text after the last quote character.

答案 1 :(得分:0)

我正在使用以下路径,并且它已成功接受。

string command1 = @"C:\test\ab ab\1.txt";
Process.Start(command1);