How to escape path containing spaces

12,616

Solution 1

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();
}

Solution 2

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.

Share:
12,616
abatishchev
Author by

abatishchev

This is my GUID. There are many like it but this one is mine. My GUID is my best friend. It is my life. I must master it as I must master my life. Without me, my GUID is useless. Without my GUID I am useless.

Updated on July 19, 2022

Comments

  • abatishchev
    abatishchev almost 2 years

    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)

  • abatishchev
    abatishchev almost 14 years
    Great! Thanks! btw, I think there is no need to string[] and IEnumerable<string> suites here well
  • abatishchev
    abatishchev almost 14 years
    i.e. Select(s => String.Format("\"{0}\"", s)). Looks great but @amarsuperstar's solution I like little bit more :) Thank you, Heinzi
  • EdmundYeung99
    EdmundYeung99 over 11 years
    doesn't work in a case where the path has a trailing "\" such as "C:\Program Files\MyApp\"
  • Can Sahin
    Can Sahin over 11 years
    @EdmundYeung99: Yes, that's a really tricky issue. The following question contains a few attempts to work around the problem: stackoverflow.com/q/5510343/87698