Problem with spaces in a filepath - commandline ex

2019-02-25 02:54发布

问题:

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.