5,448,416 members and growing! (18,169 online)
Email Password   helpLost your password?
General Programming » String handling » General     Beginner License: The Code Project Open License (CPOL)

Parsing command line arguments

By trupik

CommandLineParser library provides simple way to define command line arguments and parse them in your application
C# (C# 1.0, C# 2.0, C# 3.0, C#), Windows, .NET, Dev

Posted: 24 Apr 2008
Updated: 3 May 2008
Views: 7,093
Bookmarked: 33 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
17 votes for this Article.
Popularity: 5.01 Rating: 4.07 out of 5
0 votes, 0.0%
1
1 vote, 6.3%
2
2 votes, 12.5%
3
4 votes, 25.0%
4
9 votes, 56.3%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Although console applications are more common in 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 '-' prefix and a single character, long arguments consist of '--' 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 application 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:

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:

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:

// 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 set of arguments that cannot be used together or set of arguments, from which at least one argument must be used. This is now possible through Certifications collection of the parser and ArgumentCertification objects. They can also be defined declaratively using attributes, here is an example:

// 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.

License

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

About the Author

trupik


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

Other popular String handling articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 14 of 14 (Total in Forum: 14) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralNConsollermemberDima Pasko5:43 22 Aug '08  
GeneralBug with WPFmemberFreuk3:19 23 May '08  
GeneralRe: Bug with WPFmembertrupik9:16 26 May '08  
Generalthanksmembermezhaka5:22 21 May '08  
QuestionFurther development?memberAndreas Kroll22:41 28 Apr '08  
AnswerRe: Further development?membertrupik1:41 29 Apr '08  
GeneralRe: Further development?memberAndreas Kroll2:58 29 Apr '08  
AnswerRe: Further development?membertrupik3:03 29 Apr '08  
AnswerRe: Further development?membertrupik9:23 3 May '08  
GeneralThere are several other such articles on herememberPIEBALDconsult14:23 24 Apr '08  
GeneralRe: There are several other such articles on heremembertrupik0:30 25 Apr '08  
GeneralRe: There are several other such articles on herememberzespri23:46 4 Aug '08  
GeneralWell donememberMustafa Ismail Mustafa12:36 24 Apr '08  
GeneralRe: Well donemembertrupik12:59 24 Apr '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 May 2008
Editor:
Copyright 2008 by trupik
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project