28 January 2009

Environment.GetCommandLineArgs backslash and double-quote issue

Just noticed that System.Environment.GetCommandLineArgs() handles command line arguments that contain a backslash (\) followed by a double-quote in a strange way.

Microsoft documentation says:
"If a double quotation mark follows two or an even number of backslashes, each proceeding backslash pair is replaced with one backslash and the double quotation mark is removed. If a double quotation mark follows an odd number of backslashes, including just one, each preceding pair is replaced with one backslash and the remaining backslash is removed; however, in this case the double quotation mark is not removed."

This becomes an issue when you use double-quotes to delimit parameters that may contain spaces. If a parameter is a directory such as C:\test\ then it will be quoted as "C:\test\" but it will be returned by GetCommandLineArgs() as C:\test" ie with a double-quote instead of a backslash.

In my case, I was able to add a space between the \ and the double-quote. Then Trim() in the receiving app.

The full command line is available in the Environment.CommandLine property.

Also: a command line argument such as a"b"c is returned as abc by GetCommandLineArgs().

No comments: