3

我正在为命令行程序构建一个 gui。在 txtBoxUrls[TextBox] 文件路径中逐行输入。如果文件路径包含空格,则程序无法正常工作。该程序如下所示。

string[] urls = txtBoxUrls.Text.ToString().Split(new char[] { '\n', '\r' });

string s1;
string text;
foreach (string s in urls)
{
    if (s.Contains(" "))
    {
        s1 = @"""" + s + @"""";
        text += s1 + " ";
    }
    else
    {
        text += s + " ";
    }
}


System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;


proc.StartInfo.FileName = @"wk.exe";


proc.StartInfo.Arguments = text + " " + txtFileName.Text;

proc.StartInfo.UseShellExecute = false;


proc.StartInfo.RedirectStandardOutput = true;


proc.Start();

//Get program output
string strOutput = proc.StandardOutput.ReadToEnd();

//Wait for process to finish
proc.WaitForExit();

例如txtBoxUrls中输入的文件路径为“C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm”,程序将无法运行。这个带双引号的文件路径可以很好地在 Windows 命令行中工作(我没有使用 GUI)。有什么解决办法。

4

3 回答 3

10
proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text; 

在这一行中,text已经包含正确引用的 txtBoxUrls 字符串版本。为什么要以不带引号的形式(+ txtBoxUrls.Text)再次添加它们?如果我正确理解了您的代码,则以下内容应该有效:

proc.StartInfo.Arguments = text + " " + txtFileName.Text;    

事实上,由于txtFileName.Text可能包含空格,您也应该引用它,以确保:

proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";    

(或者,使用你的语法:)

proc.StartInfo.Arguments = text + @" """ + txtFileName.Text + @"""";    
于 2010-11-15T15:11:46.973 回答
2

通常要绕过文件名中的空格,您需要将参数用双引号括起来。如果省略引号,程序会认为它有两个参数。像这样的东西...

wk.exe "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm"

此外,这一行似乎有太多引号。四,而不是三:

s1 = @"""" + s + @"""";
于 2010-11-15T15:11:00.240 回答
0

看看 Path 类 - http://msdn.microsoft.com/en-us/library/system.io.path.aspx

Path.combine 可能是您正在寻找的。

于 2010-11-15T15:13:48.903 回答