Application Architecture in Windows Forms 2.0—Passing Command Line Arguments

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Appl. Architecture Forms

© 2006 Pearson Education, Inc.

Passing Command Line Arguments

Command line arguments allow users to determine an application’s initial state and operational behavior when launched.3 Before command line arguments can be processed to express a user’s wishes, they need to be accessed. To do this, you change your application’s entry point method, Main, to accept a string array to contain all the passed arguments:

// Program.cs
static class Program {
 [STAThread]
 static void Main(string[] args) {
  ...
 }
}

.NET constructs the string array by parsing the command line string, which means extracting substrings, delimited by spaces, and placing each substring into an element of the array. Command line syntax, which dictates which command line arguments your application can process and the format they should be entered in, is left up to you. Here is one simple approach:

// Program.cs
static class Program {
 [STAThread]
 static void Main(string[] args) {
  ...
  bool flag = false;
  string name = "";
  int number = 0;
 
  // *Very* simple command line parsing
  for( int i = 0; i != args.Length; ++i ) {
   switch( args[i] ) {
    case "/flag": flag = true; break;
    case "/name": name = args[++i]; break;
    case "/number": number = int.Parse(args[++i]); break;
    default: MessageBox.Show("Invalid args!"); return;
   }
  }
  ...
 }
}

If your static Main method isn’t where you want to handle the command line arguments for your application session, GetCommandLineArgs can come in handy for retrieving the command line arguments for the current application session:

// Program.cs
static class Program {
 [STAThread]
 static void Main() {
  ...
  string[] args = Environment.GetCommandLineArgs();
 
  // *Very* simple command line parsing
  // Note: Starting at item [1] because args item [0] is exe path
  for( int i = 1; i != args.Length; ++i ) {
   ...
  }
  ...
 }
}

You can see that GetCommandLineArgs always returns a string array with at least one item: the executable path.

Processing command line arguments is relatively straightforward, although special types of applications, known as single-instance applications, need to process command line arguments in special ways.


Previous_Page_.gif Next_Page_.gif

Personal tools