2

How can I pass Argument to the System.Dignostics.Process with spaces. I am doing this:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = exePath + @"\bin\test.exe";

string args = String.Format(@"{0}{1}{2}{3}", "-plot " ,path1, " -o ", path2);
proc.StartInfo.Arguments = args;

when path1 and path2 do not contain spaces ( Let's say path1 = C:\Temp\ and path2 = C:\Temp\Test) then it works fine, but when path1 and path2 contain spaces for example path1 = C:\Documents and Settings\user\Desktop and path2 = C:\Documents and Settings\user\Desktop\New Folder) then it trucates the path1 and path2 and abort.

Please let me know the correct way for doing this.

Thanks, Ashish

5 Answers 5

2
Process proc = new Process(); 
proc.EnableRaisingEvents = false; 
proc.StartInfo.FileName = Path.Combine(exePath, @"bin\test.exe");
proc.StartInfo.Arguments = String.Format(@"-plot ""{0}"" -o ""{1}""", path1, path2);

If using a literal (without @), you can escape the quotes:

\"{0}\"

If using a verbatim string (with @), you can double up your quotes:

""{0}""
1
  • 1
    You should be using string.Format to increase readability and therefore maintainability. Do NOT put the argument names as more parameters in the string.Format function! Commented May 31, 2012 at 17:29
1

you need to encapsulate the path in quotes. Otherwise it reads the space as a delimiter and thinks the rest of the path is an argument.

0

you could put the arguments which may contain spaces in double quotes like so:

string args = String.Format(@"{0} ""{1}"" {2} ""{3}""", "-plot", path1, "-o", path2);
0

put the paths in quotes... such as "\""+path1+"\""

0

Try the following:

string args = String.Format("{0}\"{1}\"{2}\"{3}\"", "-plot " ,path1, " -o ", path2);

This will put quotes around your paths so they are passed as a single string and spaces in them are ignored.

3
  • you need to escape the quotes in a verbatim string literal (@"") with "" and not with \" Commented Jun 18, 2009 at 12:47
  • didn't mean to be using a verbatim literal, edited my example to fix this
    – RobV
    Commented Jun 19, 2009 at 13:28
  • You should be using string.Format to increase readability and therefore maintainability. Do NOT put the argument names as more parameters in the string.Format function! Commented May 31, 2012 at 17:29