May 30, 2013

Command Line Parameter Accessors in .NET

How can strings containing white space be passed as command line parameters?
Here is the test console program:
class Program
{     
    static void Main(string[] args)
    {
        Console.WriteLine("Main(string[] args)=" + string.Join(",", args));
        Console.WriteLine("Environment.CommandLine=" + Environment.CommandLine);
        Console.WriteLine("Environment.GetCommandLineArgs()=" + string.Join(",", Environment.GetCommandLineArgs()));

        Console.WriteLine("");
        Console.WriteLine("Press any key to continue ...");
        Console.ReadKey(false);
    }
}
Using the following as command ine arguments:
Test -b:"Dummy User" "whataboutthis?" /x'Does this work' /a:another a"rgument
Produces this (the command line arguments are comma separated):
Main(string[] args)=Test,-b:Dummy User,whataboutthis?,/x'Does,this,work',/a:another,argument
Environment.CommandLine="C:\Users\...\bin\Debug\TestAccountName.vshost.exe" Test -b:"Dummy User" "whataboutthis?" /x 'Does this work' /a:another a"rgument
Environment.GetCommandLineArgs()=C:\Users\...\bin\Debug\TestAccountName.vshost.exe,Test,-b:Dummy User,whataboutthis? ,/x'Does,this,work',/a:another,argument

Looks like quotation characters "" can be used to enclose a part of a command line that contains white space, the quotation characters themselves are removed. Placing matching quotation characters around/within a command line argument ensures that it is interpreted as a single command line argument even if it contains whitespace characters. Quotation characters are stripped from the command line parameters as they are processed so they will not appear in the arguments.

Summary
Main(string[] args)
  • Gives access to ONLY the command line parameters themselves.
  • Executable is NOT included as a command line parameter.
  • Quotation marks can be used to capture a parameter or part of a parameter containing whitespace
Environment.CommandLine
  • Gives access to the raw command line
Environment.GetCommandLineArgs()
  • Gives access to ALL the command line parameters.
  • Executable is first command line parameter.
  • Quotation marks can be used to capture a parameter or part of a parameter containing whitespace

No comments: