Access Command Line Arguments in C#

Recently, one user asked me how to access command line arguments in a C# application. This how do I answers the same.

There are two common ways to read command line arguments in C#. First, you can override the Main method with an array of strings, which are command line arguments. For example, the following code loops through the command line arguments and print them on the console.

  1. static void Main(string[] args)  
  2. {  
  3.     foreach(string arg in args)  
  4.     {  
  5.        Console.WriteLine(arg);  
  6.     }  
  7.    Console.ReadLine();  
  8. }  
I compile the above code and run the exe from the command line by passing following parameters:

The output generated by the application looks like following:

However, this is not only the way to read command line arguments. For example, what if you do not want to override the Main method? Or access the command line arguments from non-Main method of your application?

You can do so using the Environment class, which has a static method called GetCommandLineArgs, which returns an array of strings containing the arguments. The following code reads the command line arguments using Environment.GetCommandLineArgs method.

  1. foreach (string arg in Environment.GetCommandLineArgs())  
  2. {  
  3.     Console.WriteLine(arg);  
  4. }  
Download and run the attached code for more details.

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.