Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape path containing spaces

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)

like image 435
abatishchev Avatar asked Sep 17 '10 08:09

abatishchev


People also ask

How do you pass a path with spaces in CMD?

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.

How do I use file paths with spaces?

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.

Can file paths have spaces?

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. ''

How do I escape special characters in CMD?

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.


2 Answers

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.

like image 100
Heinzi Avatar answered Oct 13 '22 15:10

Heinzi


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();
}
like image 38
amarsuperstar Avatar answered Oct 13 '22 17:10

amarsuperstar