Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / C#

Parsing Command Line Arguments

Rate me:
Please Sign up or sign in to vote.
4.71/5 (25 votes)
26 Apr 2009CPOL2 min read 61.8K   494   83   15
The CommandLineParser library provides a simple way to define command line arguments and parse them in your application.
For applications that have one or two arguments, you could probably manage with some switches and ifs, but when there are more arguments, you could use a CommandLineParser library and thus make your code cleaner and more elegant.

Introduction

Although console applications are more common in the Unix environment, maybe you will one day need to write one for Windows too. It is common for command line applications to accept arguments in a time-tested format that can look like this:

Finder.exe -s 3 --distinct directory1 directory2 directory3

You probably get it already - arguments can be short or long: short arguments consist of the '-' prefix and a single character, long arguments consist of the '--' prefix and a single word.

It may also be handy to support aliases for arguments (long and short name for one argument, or even more long or short names for an argument).

For applications with one or two arguments, you could probably manage with some switches and ifs, but when there are more and more arguments, you could use a CommandLineParser library and thus make your code more clean and elegant.

Examples of Use

This is the way you define arguments for your application:

C#
CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();
//switch argument is meant for true/false logic
SwitchArgument showArgument = new SwitchArgument(
    's', "show", "Set whether show or not", true);
ValueArgument<decimal> version = new ValueArgument<decimal>
    'v', "version", "Set desired version");
EnumeratedValueArgument<string> color = new EnumeratedValueArgument<string>
    'c', "color", new string[] { "red", "green", "blue" });

parser.Arguments.Add(showArgument);
parser.Arguments.Add(version);
parser.Arguments.Add(color);

And, this is how the arguments are parsed:

C#
try 
{
    parser.ParseCommandLine(args); 
    parser.ShowParsedArguments();
 
    // now you can work with the arguments ... 

    // if (color.Parsed) ... test, whether the argument appeared on the command line
    // {
    //     color.Value ... contains value of the level argument
    // } 
    // if (showArgument.Value) ... test the switch argument value 
    //     ... 
}
catch (CommandLineException e)
{
    Console.WriteLine(e.Message);
}

You can find more examples of use in the documentation file.

The other way to use the library is to declare arguments by using attributes and thus make your code even more elegant:

C#
// fields of this class will be bound
class ParsingTarget
{
    //class has several fields and properties bound to various argument types

    [SwitchArgument('s', "show", true, Description = "Set whether show or not")]
    public bool show;

    private bool hide;
    [SwitchArgument('h', "hide", false, Description = "Set whether hid or not")]
    public bool Hide
    {
        get { return hide; }
        set { hide = value; }
    }

    [ValueArgument(typeof(decimal), 'v', "version", 
     Description = "Set desired version")]
    public decimal version;

    [ValueArgument(typeof(string), 'l', "level", 
     Description = "Set the level")]
    public string level;

    [ValueArgument(typeof(Point), 'p', "point", 
     Description = "specify the point")]
    public Point point;

    [BoundedValueArgument(typeof(int), 'o', "optimization", 
        MinValue = 0, MaxValue = 3, Description = "Level of optimization")]
    public int optimization;

    [EnumeratedValueArgument(typeof(string),'c', "color", 
     AllowedValues = "red;green;blue")]
    public string color;
}

As Andreas Kroll pointed out, it can be useful to define a set of arguments that cannot be used together, or a set of arguments from which at least one argument must be used. This is now possible through the Certifications collection of the parser and the ArgumentCertification objects. They can also be defined declaratively using attributes. Here is an example:

C#
// exactly one of the arguments x, o, c must be used
[ArgumentGroupCertification("x,o,c", EArgumentGroupCondition.ExactlyOneUsed)]
// only one of the arguments f, u must be used
[ArgumentGroupCertification("f,u", EArgumentGroupCondition.OneOreNoneUsed)]
// arguments j and k can not be used together with arguments l or m
[DistinctGroupsCertification("j,k","l,m")]
public class Archiver
{
    [ValueArgument(typeof(string), 'f', "file", Description="Input from file")]
    public string InputFromFile;

    [ValueArgument(typeof(string), 'u', "url", Description = "Input from url")]
    public string InputFromUrl;

    [ValueArgument(typeof(string), 'c', "create", Description = "Create archive")]
    public string CreateArchive;

    [ValueArgument(typeof(string), 'x', "extract", Description = "Extract archive")]
    public string ExtractArchive;

    [ValueArgument(typeof(string), 'o', "open", Description = "Open archive")]
    public string OpenArchive;

    [SwitchArgument('j', "g1a1", true)]
    public bool group1Arg1;

    [SwitchArgument('k', "g1a2", true)]
    public bool group1Arg2;

    [SwitchArgument('l', "g2a1", true)]
    public bool group2Arg1;

    [SwitchArgument('m', "g2a2", true)]
    public bool group2Arg2;
}

Conclusion

The library is rather simple - it was just a school homework after all, but maybe someone will find it useful.

The latest release can be downloaded from CodePlex: http://commandlineparser.codeplex.com/.

History

  • 24th April, 2008: Initial version

License

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


Written By
Software Developer (Junior)
Czech Republic Czech Republic
I am a computer science student at Charles University in Prague. I work as a developer of CRM and informational systems.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Pravin Patil, Mumbai11-Oct-11 23:24
Pravin Patil, Mumbai11-Oct-11 23:24 
GeneralNConsoller Pin
Dima Pasko22-Aug-08 4:43
Dima Pasko22-Aug-08 4:43 
GeneralBug with WPF Pin
Freuk23-May-08 2:19
Freuk23-May-08 2:19 
GeneralRe: Bug with WPF Pin
trupik26-May-08 8:16
trupik26-May-08 8:16 
Generalthanks Pin
mezhaka21-May-08 4:22
mezhaka21-May-08 4:22 
QuestionFurther development? Pin
Andreas Kroll28-Apr-08 21:41
Andreas Kroll28-Apr-08 21:41 
AnswerRe: Further development? Pin
trupik29-Apr-08 0:41
trupik29-Apr-08 0:41 
GeneralRe: Further development? Pin
Andreas Kroll29-Apr-08 1:58
Andreas Kroll29-Apr-08 1:58 
AnswerRe: Further development? Pin
trupik29-Apr-08 2:03
trupik29-Apr-08 2:03 
AnswerRe: Further development? Pin
trupik3-May-08 8:23
trupik3-May-08 8:23 
GeneralThere are several other such articles on here Pin
PIEBALDconsult24-Apr-08 13:23
mvePIEBALDconsult24-Apr-08 13:23 
GeneralRe: There are several other such articles on here Pin
trupik24-Apr-08 23:30
trupik24-Apr-08 23:30 
GeneralRe: There are several other such articles on here Pin
zespri4-Aug-08 22:46
zespri4-Aug-08 22:46 
GeneralWell done Pin
Mustafa Ismail Mustafa24-Apr-08 11:36
Mustafa Ismail Mustafa24-Apr-08 11:36 
GeneralRe: Well done Pin
trupik24-Apr-08 11:59
trupik24-Apr-08 11:59 

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.