How To Use Command Line Arguments in .NET

  • google plus

In Brief...

The steps below describe how to use command-line arguments in .NET

Command line arguments are values passes to an application at execution time. All .Net applications (except services and class libraries) are capable of receiving command line arguments. In most cases, the implementation of command line arguments is incududed in the templates used to create the application.

The way we handle command line arguments in C# and Visual Basic is slightly different, so we will examine each language seperately. Lets begin by looking at C#.

Instructions

  1. In C#, the templates generally include an array of type string in the Main method entry point. For example, here we see the Main method signature in a standard console application.
    
            static void Main(string[] args) { }
    
  2. In order to access the values passed as parameters, we simply need to iterate through the collection and extract the values. For Example:
    
    	static void Main(string[] args)
            {
                foreach (string param in args)
                {
                    Console.WriteLine(param);
                }
                Console.ReadLine();
            }
    
  3. Once compiled, we can execute the application using the following command:
    
    	ConsoleApp3.exe alpha bravo charlie delta
    
  4. This will return the following result:
    Result of executing ConsoleApp3 with parameters

Now, lets take a look at Visual Basic.

  1. VB is slightly different because there is no array explicitly declared as a parameter to the Main method. If we build a default VB console application, we will see a method signature that looks like this;
    
    	Sub Main()
    
    	End Sub
    
  2. But even though the array is not explicitly passed as a parameter, the argument values are still available. We simply access them using the "My" namespace. For example;
    
        Sub Main()
            For Each param As String In My.Application.CommandLineArgs
                Console.WriteLine(param)
            Next param
            Console.ReadLine()
        End Sub
    
  3. Once compiled, we can execute the application using the following command:
    
    	ConsoleApp1.exe alpha bravo charlie delta
    
  4. This will return the following result:
    Result of executing ConsoleApp1 with parameters

Author: Michael Osborne

Discuss