Problem with spaces in a filepath - commandline execution in C#
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 + @"""";
Solution 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 + @"""";
Comments
-
Vinod almost 2 years
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.
-
Vinod over 13 yearsThanks. Actually proc.StartInfo.Arguments = text + @" """ + txtFileName.Text + @""""; didn't work. proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\""; Works.
-
Lane over 13 yearsNo, his quoting is correct. It produces his intended result: "s". I checked this in VS a minute ago.
-
jocull over 13 yearsYou can rule that out in this instance then. Just something to consider when working with the command-line.
-
Can Sahin over 13 years@Vinod: That's strange, since both should be equivalent. Anyway, thanks for the feedback!
-
Bahamut over 10 yearsThis fixed my problem! Thanks dude