Friday, February 16, 2018

C# .NET - How to get exact Command (CMD) Line Arguments as Entered by User - Verbatim Echo

So many wrong ways to do this, and they are litter all over Stack Overflow. 

Many solutions follow Microsoft's documentation of iterating over the arguments array and output it as an interpreted string format. This is not necessarily the format that was inputted by the user! 

This is how to get the exact command line arguments as entered by the user.


string AppCMDName = Environment.GetCommandLineArgs()[0]; 
//gets fully qualified application name with or without .exe specified  
//but does not get surrounding double quotes used to qualify the
//cmd line path that may contain spaces. Single quotes not allowed in a path.
string commandLine = Environment.CommandLine.Replace(AppCMDName, "").TrimEnd();
if (commandLine.StartsWith("\"\""))
    commandLine = commandLine.Substring(2, commandLine.Length - 2).TrimStart(); 
    //remove surrounding quotes if used to specify cmd


Typical iteration over args array example from https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/how-to-display-command-line-arguments


class CommandLine
{ 
    static void Main(string[] args)
    {
        // The Length property provides the number of array elements
        System.Console.WriteLine("parameter count = {0}", args.Length);

        for (int i = 0; i < args.Length; i++)
        {
            System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }
    }
}
/* Output (assumes 3 cmd line args): 
    parameter count = 3
    Arg[0] = [a]
    Arg[1] = [b]
    Arg[2] = [c]
*/

No comments:

Post a Comment