Passing the Command Line Arguments in .NET

Even with modern UI, we often need a way to start our programs with specific parameters. Command-line arguments are helpful to provide those parameters without exposing them to everybody. When developing with .NET and C# you can get the command line arguments from your Main(string[] Args) function. Args is in fact an array containing all the strings separated by spaces entered in the command line.
 
Suppose we have an application that accepts some command line parameters to do some operations. We know how to pass the parameters from the command prompt. I have a sample here.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication2010  
  7. {  
  8.     class CommandLineArgument  
  9.     {  
  10.         static void Main(string[] arguments)  
  11.         {  
  12.             foreach (String arg in Environment.GetCommandLineArgs())  
  13.             {  
  14.                 Console.Write(arg);  
  15.             }  
  16.             Console.ReadKey();  
  17.         }  
  18.     }  
Now I am going to introduce passing the command line arguments from Visual Studio. Sometimes we don't like to pass the arguments from the Command Prompt. Here is a quick way to pass the arguments.
 
Visual Studio enables a nice feature where you can do this in the Project Properties window, on the Debug tab. Here are the steps to achieve this
  1. Right, Click on Project from Solution Explorer and select Properties.
  2. In the Project Properties Windows, Navigate to "Debug Tab"
  3. You will find the text box "Command Line".
Please separate the arguments with the comma(',') or Space also.
 
Here the ScreenShot to pass the arguments
 
CmdArg1.gif
 
Here the source code follows :
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication2010  
  7. {  
  8.     class CommandLineArgument  
  9.     {  
  10.         static void Main(string[] arguments)  
  11.         {  
  12.             foreach (String arg in arguments)  
  13.             {  
  14.                 Console.Write(arg);  
  15.             }  
  16.             Console.Write("Waiting for User response...");  
  17.             Console.ReadKey();  
  18.         }  
  19.     }  
Here I put the breakpoint to give a clear view of the arguments passed from the Debug Tab.
 
CmdArg2.gif
 
The final output is shown here
 
CmdArg3.gif
 
I thought this article would be helpful to all. Any suggestions are welcome.
 
Happy Coding :-)


Recommended Free Ebook
Similar Articles