Vin*_*nod 3 c# command-line filepath
我正在为命令行程序构建一个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();
Run Code Online (Sandbox Code Playgroud)
例如,如果在txtBoxUrls中输入的文件路径是"C:\ VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm",则该程序将无法运行.这个带双引号的文件路径可以很好地在windows命令行(我没有使用GUI)中工作.什么是解决方案.
Hei*_*nzi 10
proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text;
Run Code Online (Sandbox Code Playgroud)
在这一行中,text已经包含了txtBoxUrls字符串的正确引用版本.为什么要以不带引号的形式(+ txtBoxUrls.Text)再次添加它们?如果我理解你的代码,以下应该有效:
proc.StartInfo.Arguments = text + " " + txtFileName.Text;
Run Code Online (Sandbox Code Playgroud)
事实上,既然txtFileName.Text可能包含空格,你也应该引用它,只是为了确定:
proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";
Run Code Online (Sandbox Code Playgroud)
(或者,使用你的语法:)
proc.StartInfo.Arguments = text + @" """ + txtFileName.Text + @"""";
Run Code Online (Sandbox Code Playgroud)