Click here to Skip to main content
13,298,655 members (68,152 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


121 bookmarked
Posted 5 Mar 2010

C#/.NET Command Line Argument Parser Reloaded

, 24 Aug 2017
Rate this:
Please Sign up or sign in to vote.
Easy to use yet powerful command line argument parser which also creates usage and parameter information for the user.


Many programs use command line arguments. Each time parsing has to be done in the same way. There are other projects which facilitate the parsing process. For example, C#/.NET Command Line Arguments Parser does a great job, however it lacks verification of the passed and parsed arguments. C# command-line option parser can do that, however using it is quite complicated. CLAParser is a compromise of both: It is easy to use and uses regular expressions for parsing and validating which makes it quite powerful. Further more, it supports i18n and it creates information for correct command line usage for the user.

Naming Conventions

  • Arguments: Everything passed on argument line to program separated by spaces, or grouped by quotes, e.g.
    program.exe argument1 /argument2 
    	--argument3 .!§$argument4´ß2! "argument5 with spaces"
  • Parameter: All arguments that start with / or -, e.g.
    program.exe /parameter1 -parameter2
  • Values: Every argument that is not a parameter, e.g.
    program.exe value1 value2 /my_param  'v a l u e 3'

In the last example, value1 and value2 are values without parameters, whereas v a l u e 3 belongs to parameter my_param. (Note that the single quotes which hold 'v a l u e 3' together are removed by CLAParser.)

Using the Code

  1. Copy CLAParser files to your project folder and include them in C# project (CmdLineArgumentParser.cs, CmdLineArgumentParserRes.resx, and optionally further resx-files).

    project explorer

  2. Create a CLAParser instance by calling the constructor.
    CLAParser.CLAParser CmdLine = new CLAParser.CLAParser("CLAParserTest");
    The argument must be the default namespace. (This is necessary so that CLAParser can find its resx-files.)
  3. Use CmdLine.Parameter() function to define known parameters.
        "", CLAParser.CLAParser.ValueType.String,
        "Path to file that is to be loaded on starting the program.");
        "output", CLAParser.CLAParser.ValueType.OptionalString,
        "Write output to file, if no file specified default file output.txt is used.");
    CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Required, "add",
        "Do a mathematical addition of number given integers.");
  4. Start parsing by calling function CmdLine.Parse(). Raised exceptions can be passed directly to the user. They indicate the reason for the problem. Further, show user correct syntax and information about the parameters using CmdLine.GetUsage() and CmdLine.GetParameterInfo().
    catch (CLAParser.CLAParser.CmdLineArgumentException Ex)
  5. If arguments are correct and all required arguments are defined, no exception is raised and values of all parameters can be accessed by the dictionary interface. Optional parameters which are not defined by the user are indicated by null values. A value without parameter can be accessed by the empty string ("").
    if(CmdLine[""] != null)
        value = CmdLine[""];
    if(CmdLine["parameter"] != null)
        value = CmdLine["parameter"];

Points of Interest

  • Update: Using the obsolete function Parse(string[] Arguments) with args as parameter quotes (") must be escaped (\") to be recognized correctly. It is recommended to use function Parse() instead!
  • Function FindMismatchReasonInRegex() helps in analyzing why a search string does not match a regular expression and indicates where the problem probably is located.
  • CLAParser is internationalized, i.e. new languages can easily be defined by creating new resx-files (localization).
  • Using the enumerator, all arguments can be traversed, e.g.:
    IEnumerator e = CmdLine.GetEnumerator();
    while (e.MoveNext())
        DictionaryEntry arg = (DictionaryEntry)e.Current;
        Console.WriteLine(arg.Key + "=" + arg.Value);
  • For a complete overview of CLAParser's capabilities, have a look at the attached code files.


  • 2010-02-24
    • Initial release
  • 2010-04-05
    • CmdLineArgumentParser.cs:574 -> from "...Parameters == false)" to "...Parameters == true)"
  • 2011-01-06
    • Corrected error in regular expression which made it impossible to use more than one quoted value
    • Added internal function GetRawCommandlineArgs() proposed by vermis0. Together with it comes function Parse() which makes function Parse(string[] Arguments) obsolete. Now the quotes of quoted values (e.g. "value with spaces") do not need to be escaped anymore!
  • 2011-01-07
    • Corrected error in regular expression which made it impossible to use a value without parameter containing minus (-) or slash (/).
    • Made behaviour with (first) value without parameter more consistent. Instead of setting AllowValuesWithoutParameter, use function Parameter() with ParameterName=="".
    • Fixed error with case sensitivity of parameter. Now everything is case insensitive.
  • 2011-09-09
    • Corrected problem reported by Hautzendorfer concerning single parameters not being processed correctly
  • 2014-07-09
    • Corrected problem reported by Gray John concerning multiple boolean parameters not being processed correctly
  • 2015-11-07
    • Corrected problem detecting values without parameters
    • Added tests
  • 2017-08-24
    • Enhance formatting if help text for parameter contains line break (\n)
    • Added GetAdditionalParameters() for nested usage of CLAParser


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Julian Ohrt
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
VivianMC10-Nov-15 23:51
memberVivianMC10-Nov-15 23:51 
BugProblem with multiple Bool parms Pin
Gray John5-Mar-14 9:58
memberGray John5-Mar-14 9:58 
AnswerRe: Problem with multiple Bool parms Pin
Julian Ohrt9-Jul-14 5:12
memberJulian Ohrt9-Jul-14 5:12 
SuggestionSimple Command Line Arguments Parser Pin
Member 14778522-Mar-12 6:31
memberMember 14778522-Mar-12 6:31 
QuestionSomething more Functional Pin
Alois Kraus9-Sep-11 13:26
memberAlois Kraus9-Sep-11 13:26 
AnswerRe: Something more Functional Pin
Julian Ohrt10-Sep-11 0:47
memberJulian Ohrt10-Sep-11 0:47 
GeneralRe: Something more Functional Pin
Alois Kraus10-Sep-11 0:58
memberAlois Kraus10-Sep-11 0:58 
GeneralIsn't there a problem ... Pin
Hautzendorfer23-May-11 10:54
memberHautzendorfer23-May-11 10:54 
AnswerRe: Isn't there a problem ... Pin
Julian Ohrt9-Sep-11 3:55
memberJulian Ohrt9-Sep-11 3:55 
QuestionFxCop Compliance Pin
Dave Hary8-Jan-11 9:13
memberDave Hary8-Jan-11 9:13 
AnswerRe: FxCop Compliance Pin
leppie10-Jan-11 0:04
memberleppie10-Jan-11 0:04 
GeneralRe: FxCop Compliance Pin
PIEBALDconsult21-Sep-13 11:04
professionalPIEBALDconsult21-Sep-13 11:04 
AnswerRe: FxCop Compliance Pin
Julian Ohrt9-Sep-11 3:59
memberJulian Ohrt9-Sep-11 3:59 
GeneralSuggestion on using Environment.CommandLine Pin
vermis06-Dec-10 10:53
membervermis06-Dec-10 10:53 
You might want to consider working with a more "raw" version of the command line that goes into your .Parse so you can have more consistent parsing. If you use the snippet below, you won't have to worry about what pre-processing .NET might have done to the args[] (like string escape handling). I ran out of time so I don't know what code changes are required to support this in your library.

/// <summary>This will return the raw unprocessed command line parameters as a string.</summary>
/// <returns></returns>
/// <remarks>Essentially, we are taking the unprocessed CommandLine and removing the executable path prefix by comparison to the .NET processed CommandLineArg[0].</remarks>
static public string GetRawCommandlineArgs() {			
  string Raw = Environment.CommandLine;
  string ExecutablePath = Environment.GetCommandLineArgs()[0];
  string Parsed;
  // Raw is the completely unprocessed commandline the OS used to launch our application. This includes the
  // path used to launch the executable as well as the parameters.
  // Our ExecutablePath is the .NET parsed path to the executable used to launch this application.
  // It can be a relative or absolute path. Since it was parsed by .NET, if the OS passed the executable
  // path as an encapsulated string, the surrounding " have been removed.
  // If the raw commandline starts with a ", then we need to take that into account when we chop off
  // the executable path prefix (it was parsed out by .NET in ExecutablePath).
  if (Raw.StartsWith("\"")) {
    Parsed = Raw.Substring(ExecutablePath.Length + 2);
  } else {
    Parsed = Raw.Substring(ExecutablePath.Length);
  // Trim any leading spaces (there can be one or two depending on how the executable was launched)
  Parsed = Parsed.TrimStart(' ');
  return Parsed;

The whole reason I went down this path is because for the life of me I couldn't figure out how to pass these parameters!

This will return 'Unknown parameter found: "01\product;Integrated".'
<br />
my.exe /ConnectionString "Data Source=Server-01\product;Integrated Security=true;" /ScriptFile "file-00.ext"<br />

This will return 'A required parameter is missing! Parameter "ScriptFile" is required but missing!'
<br />
my.exe /ConnectionString "\"Data Source=Server-01\product;Integrated Security=true;\"" /ScriptFile "\"file-00.ext\""<br />

GeneralRe: Suggestion on using Environment.CommandLine Pin
Heinz JKarl Otta Fritz6-Jan-11 4:11
memberHeinz JKarl Otta Fritz6-Jan-11 4:11 
GeneralWorks great Pin
ssm629716-Jul-10 7:21
memberssm629716-Jul-10 7:21 
QuestionWhat about... Pin
kornman005-Mar-10 6:40
memberkornman005-Mar-10 6:40 
AnswerRe: What about... Pin
MarkLTX5-Mar-10 7:33
memberMarkLTX5-Mar-10 7:33 
GeneralRe: What about... Pin
kornman005-Mar-10 8:16
memberkornman005-Mar-10 8:16 
GeneralRe: What about... Pin
Heinz JKarl Otta Fritz5-Apr-10 4:09
memberHeinz JKarl Otta Fritz5-Apr-10 4:09 
GeneralI like what you have done, but alas someone beat you to it Pin
Sacha Barber5-Mar-10 2:18
mvpSacha Barber5-Mar-10 2:18 
GeneralRe: I like what you have done, but alas someone beat you to it Pin
Heinz JKarl Otta Fritz5-Apr-10 4:16
memberHeinz JKarl Otta Fritz5-Apr-10 4:16 
GeneralRe: I like what you have done, but alas someone beat you to it Pin
Darek Danielewski10-Jun-15 9:31
memberDarek Danielewski10-Jun-15 9:31 
GeneralRe: I like what you have done, but alas someone beat you to it Pin
mbearden16-Jul-15 9:12
membermbearden16-Jul-15 9:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 24 Aug 2017
Article Copyright 2010 by Julian Ohrt
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid