Showing posts with label Command line arguments. Show all posts
Showing posts with label Command line arguments. Show all posts

Sunday, February 13, 2011

How to pass Command line arguments in C#

 To pass command line argument, create a windows form application and the Main() method should look like:

       [STAThread]
        static void Main()
        {
                string[] args = Environment.GetCommandLineArgs();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1(args[1], int.Parse(args[2])));
        }
Here,
  Method Environment.GetCommandLineArgs() accepts arguments for this application.
  new Form1(args[1], int.Parse(args[2])) this code segment is passing the  parameters to the constructor, args[1] is for Name, args[2] is for Year of Birth and missing args[0] contains the current executing exe path.

This is the code segment for the constructor accepting parameters:
 public Form1(string Name, int YearOfBirth)
 {             MessageBox.show(string.Format(" NAME :: {0} \n Your year of Birth :: {1}",      
                 Name,YearOfBirth.ToString()));
  }
        
For testing goto command prompt and execute:
 TestArguments.exe "Ahmed" 1980
Or,

 System.Diagnostics.Process.Start(@"TestArguments.exe", "Ahmed " + " 1980" );