To pass a path with spaces to .NET console application you should escape it. Probably not escape but surround with double quotes:
myapp.exe --path C:\Program Files\MyApp`
becomes
new string[] { "--path", "C:\Program", "Files\MyApp" }
but
myapp.exe --path "C:\Program Files\MyApp"
becomes
new string[] { "--path", "C:\Program Files\MyApp" }
and it works fine and you can parse that easily.
I want to extend the set of parameters given with an addition one and start a new process with the resulting set of parameters:
new ProcessStartInfo(
Assembly.GetEntryAssembly().Location,
String.Join(" ", Enumerable.Concat(args, new[] { "--flag" })))
This becomes myapp.exe --path C:\Program Files\MyApp --flag
where path drops its escaping.
How to workaround it with common solution? (without searching each parameter's value requiring escaping and quoting it manually)
Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.
Newer versions of Windows allow the use of long file names that can include spaces. If any of the folder or file names used on the command line contain spaces, you must enclose the path in quotes or remove spaces and shorten longer names to eight characters.
All filenames and paths which contain spaces must be quoted. This answer is only a partial solution: It will work if there are spaces in the path but it will not work if there are spaces in the filename. Calling ''start "b a.exe" fails. ''
If you need to use any of these characters as part of a command-line argument to be given to a program (for example, to have the find command search for the character >), you need to escape the character by placing a caret (^) symbol before it.
Just quote every parameter. This...
myapp.exe "--path" "C:\Program Files\MyApp" "--flag"
...is a perfectly valid command line and does exactly what you want.
I don't think it is possible since the space is the delimiter for CLI arguments so they would need to be escaped.
You could extract this into an extension method quite nicely so you can just run args.Escape()
in your code above.
public static string[] Escape(this string[] args)
{
return args.Select(s => s.Contains(" ") ? string.Format("\"{0}\"", s) : s).ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With