Problem with spaces in a filepath - commandline execution in C#

落花浮王杯 提交于 2019-12-01 22:55:38

问题


I am building a gui for a commandline program. In txtBoxUrls[TextBox] file paths are entered line by line. If the file path contains spaces the program is not working properly. The program is given below.

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

For example if the file path entered in txtBoxUrls is "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm", The program will not work. This file path with double quotes will work in the windows command line(I am not using the GUI) nicely. What would be the solution.


回答1:


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

In this line, text already contains the properly quoted version of your txtBoxUrls strings. Why do you add them again in unquoted form (+ txtBoxUrls.Text)? If I understood your code corrently, the following should work:

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

In fact, since txtFileName.Text could probably contain spaces, you should quote it as well, just to be sure:

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

(or, using your syntax:)

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



回答2:


Usually to get around spaces in filenames, you'll need to wrap your argument in double quotes. If you leave out the quotes the program will think it has two arguments. Something like this...

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

Also, this line appears to have too many quotes. Four, instead of three:

s1 = @"""" + s + @"""";



回答3:


Take a look at the Path class - http://msdn.microsoft.com/en-us/library/system.io.path.aspx

Path.combine might be what you are looking for.



来源:https://stackoverflow.com/questions/4185633/problem-with-spaces-in-a-filepath-commandline-execution-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!