With this program (cs.exe
):
class Program
{
static void Main(string[] args)
{
foreach (var item in args)
{
Console.WriteLine(item);
}
}
}
And run:
> cs.exe go\to\a_path
go\to\a_path
> cs.exe "go\to\a path"
go\to\a path
> cs.exe "go\to\a path\"
go\to\a path"
> cs.exe 'go\to\a path\'
'go\to\a
path\'
That means if your path has a space so you quote it, be very careful NOT to put a trailing \
at the end, otherwise your program
might just not be able to handle it as it incorrectly contains a "
at the end. Single quote is even weirder!
PowerShell exhibits a similar behavior but without the difference between single and double quotes.
How do I understand this behavior? What's the underlying rule to evaluate backslash in cmd so this can be explained consistently?
As you are not calling an internal
cmd
command, but calling an executable file, this behaviour is not caused bycmd
but the command line argument parser routines. In windows, programs don't receive a collection/array/set of arguments, but a string with all the arguments and each program tokenizes this string to obtain each element. This is usually done by routines included by the compiler that hides this operation and exposes to the code an easier way to handle arguments.Documentation for the C Command-Line argument parser states that
There is also a set of undocumented/non official rules (How Command Line Parameters Are Parsed)
The
.Net
argument parsing rules are just a derivation of those rules. If you need a different behaviour, then you should use theEnvironment.CommandLine
property to retrieve the full command line string and write your own parsing code.