65.9K
CodeProject is changing. Read more.
Home

Yet Another Command Line Parser

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.31/5 (8 votes)

Mar 5, 2008

CPOL
viewsIcon

38631

downloadIcon

909

A simple to use C# Command Line parser.

Introduction

This is a basic command-line argument parser. Most parsers I have found try to do too much, such as default parameter support that requires a complicated setup. This utility simply parses the command line arguments into argument/value pairs and a list of single parameters. It is up to the user to figure out what to do after that.

Background

Parsing command line arguments is a common step in console applications. I needed a simple way of doing this without having to register a bunch of event handlers or complicated argument patterns. It also needed to support the most common argument flags ("-", "--", and "/"), as well as handle values with spaces in them (such as file paths).

Using the code

The code is extremely easy to use. Simply call the Parse() method on the CommandLine class with the string[] of arguments you wish to parse. Then, extract the arguments and parameters from the returned CommandArgs.

For example:

static void Main(string[] args) 
{ 
   // parse the command line into arguments and parameters 
   CommandArgs commandArgs = CommandLine.Parse(args); 

   // output all the argument pairs 
   Console.WriteLine("Command Line Arguments:"); 
   foreach ( KeyValuePair<string, string> pair in commandArgs.ArgPairs ) 
   { 
      Console.WriteLine( string.Format( " {0} = {1}", pair.Key, pair.Value )); 
   } 

   // output all the parameters 
   Console.WriteLine("\nCommand Line Parameters:"); 
   foreach ( string param in commandArgs.Params ) 
   { 
      Console.WriteLine( " " + param ); 
   } 
}

History

  • Release 1.0.0.0 - 3/5/2008.