Click here to Skip to main content
12,070,248 members (39,331 online)
Click here to Skip to main content
Add your own
alternative version


252 bookmarked

C#/.NET Command Line Arguments Parser

, 5 Nov 2002 MIT
Rate this:
Please Sign up or sign in to vote.
Class to parse command line arguments and store/retrieve them.


Even with modern UI, we often need a way to start our programs with specific parameters. Command line arguments are helpful to provide those parameters without exposing them to everybody. When developing with .NET and C# you can get the command line arguments from your Main(string[] Args) function. Args is in fact an array containing all the strings separated by spaces entered in the command line. What the following class does is to transform this array of strings into a ready to use collection of key/value pairs. You can then easily find and get from this collection a specific value for one of your parameters (key).

The Arguments class

This class parses your command line arguments, find all parameters starting with -, -- or / and all the values linked. I assumed that a value could be separated from a parameter with a space, a : or a =. The parser also look for enclosing characters like ' or " and remove them. Of course if you have a value like 'Mike's house', only the first and last ' will be removed. To achieve its goal, the class relies heavily on the regular expressions capabilities of .NET. The first regular expression (^-{1,2}|^/|=|:) splits one argument into several parts:

  • the parameter
  • the value

This regular expression handles cases where only a parameter is present, only a value is present or if both are present. The program performs accordingly to the number of parts found. The second regular expression (^['"]?(.*?)['"]?$) is used to detect and remove all starting and trailing ' or " characters from a value. When all your arguments are parsed, retrieving a value from a parameter is as easy as writing MyValue=params["MyParam"]. If the parameter doesn't exist or was not in the command line then you will get a null reference you can test against.

using System;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace CommandLine.Utility
    /// <summary>
    /// Arguments class
    /// </summary>
    public class Arguments{
        // Variables
        private StringDictionary Parameters;

        // Constructor
        public Arguments(string[] Args)
            Parameters = new StringDictionary();
            Regex Spliter = new Regex(@"^-{1,2}|^/|=|:",

            Regex Remover = new Regex(@"^['""]?(.*?)['""]?$",

            string Parameter = null;
            string[] Parts;

            // Valid parameters forms:
            // {-,/,--}param{ ,=,:}((",')value(",'))
            // Examples: 
            // -param1 value1 --param2 /param3:"Test-:-work" 
            //   /param4=happy -param5 '--=nice=--'
            foreach(string Txt in Args)
                // Look for new parameters (-,/ or --) and a
                // possible enclosed value (=,:)
                Parts = Spliter.Split(Txt,3);

                // Found a value (for the last parameter 
                // found (space separator))
                case 1:
                    if(Parameter != null)
                            Parts[0] = 
                                Remover.Replace(Parts[0], "$1");

                            Parameters.Add(Parameter, Parts[0]);
                    // else Error: no parameter waiting for a value (skipped)

                // Found just a parameter
                case 2:
                    // The last parameter is still waiting. 
                    // With no value, set it to true.
                            Parameters.Add(Parameter, "true");

                // Parameter with enclosed value
                case 3:
                    // The last parameter is still waiting. 
                    // With no value, set it to true.
                    if(Parameter != null)
                            Parameters.Add(Parameter, "true");

                    Parameter = Parts[1];

                    // Remove possible enclosing characters (",')
                        Parts[2] = Remover.Replace(Parts[2], "$1");
                        Parameters.Add(Parameter, Parts[2]);

            // In case a parameter is still waiting
            if(Parameter != null)
                    Parameters.Add(Parameter, "true");

        // Retrieve a parameter value if it exists 
        // (overriding C# indexer property)
        public string this [string Param]

The test class

Here is an example of how to use the Arguments class. As usual, the code is available in the zip file.

using System;
using CommandLine.Utility;

namespace CommandLine
    /// <summary>
    /// Testing class
    /// </summary>
    class Test
        /// <summary>
        /// Main loop
        /// </summary>
        static void Main(string[] Args)
        // Command line parsing
        Arguments CommandLine=new Arguments(Args);

        // Look for specific arguments values and display 
        // them if they exist (return null if they don't)
        if(CommandLine["param1"] != null) 
            Console.WriteLine("Param1 value: " + 
            Console.WriteLine("Param1 not defined !");

        if(CommandLine["height"] != null) 
            Console.WriteLine("Height value: " + 
            Console.WriteLine("Height not defined !");

        if(CommandLine["width"] != null) 
            Console.WriteLine("Width value: " + 
            Console.WriteLine("Width not defined !");

        if(CommandLine["size"] != null) 
            Console.WriteLine("Size value: " + 
            Console.WriteLine("Size not defined !");

        if(CommandLine["debug"] != null) 
            Console.WriteLine("Debug value: " + 
            Console.WriteLine("Debug not defined !");

        // Wait for key
        Console.Out.WriteLine("Arguments parsed. Press a key");

Execution sample

I provided the following command line as the Arguments setting in the properties dialog of the Visual Studio .NET solution included in the ZIP file: -size=100 /height:'400' -param1 "Nice stuff !" --debug that command line produced the following output

Param1 value: Nice stuff !
Height value: 400
Width not defined !
Size value: 100
Debug value: true
Arguments parsed. Press a key...


In this article with saw how to parse, store and retrieve the arguments line of a .NET application. This class is versatile enough to handle a lot of different kind of arguments. Compatible with most of the forms we are used to (-param, --param or Windows /param). Thanks to the regular expressions for this. Using regular expressions allowed us to keep the Arguments class very small and the usage is very simple. Regular expressions are very powerful and can be used for most of your parsing needs (as far as speed is not the main concern).

Special thanks to: Benjamin, Guillaume and Sebastien for their support Blush | :O )

Happy Coding!!!


  • October 28, 2002 - v1.0 Initial release
  • November 6, 2002 - v1.1 Bug fix. Should be bug free now. Thanks to n2s for help.


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Software Developer (Senior) Siliconz Ltd
New Zealand New Zealand
Richard Lopes
Just Programmer

You may also be interested in...

Comments and Discussions

PraiseExcellent ! Pin
h1403024-Dec-15 16:16
memberh1403024-Dec-15 16:16 
QuestionArgs[0] as path Pin
NikolaB11-Nov-14 0:53
memberNikolaB11-Nov-14 0:53 
QuestionAnother solution Pin
Alan M Donnelly12-May-14 12:46
memberAlan M Donnelly12-May-14 12:46 
QuestionI love this command line parser Pin
raylitalo18-Feb-14 4:25
memberraylitalo18-Feb-14 4:25 
GeneralMy vote of 5 Pin
urinspiration7-Jan-14 22:51
memberurinspiration7-Jan-14 22:51 
GeneralMy vote of 5 Pin
Belgian Ducky12-Aug-13 23:19
memberBelgian Ducky12-Aug-13 23:19 
Questiongood Pin
Hua Yujun6-Apr-13 22:48
memberHua Yujun6-Apr-13 22:48 
SuggestionJust 3 lines Pin
Sven Johannsen22-Mar-13 5:01
memberSven Johannsen22-Mar-13 5:01 
QuestionCommand line parser with linq Pin
masterluke18-Jan-13 23:54
membermasterluke18-Jan-13 23:54 
GeneralMy vote of 5 Pin
Vincebl28-Nov-12 9:46
memberVincebl28-Nov-12 9:46 
Helpful and exactly what I was searching
QuestionReally helpful Pin
missdeborah4-Jun-12 10:43
membermissdeborah4-Jun-12 10:43 
SuggestionAnother simple Command Line Arguments Parser Pin
Member 14778522-Mar-12 6:08
memberMember 14778522-Mar-12 6:08 
SuggestionArgument with space with file path as value fix PinPopular
tbare13-Sep-11 7:30
membertbare13-Sep-11 7:30 
GeneralRe: Argument with space with file path as value fix Pin
hansmustermann9-Nov-12 4:59
memberhansmustermann9-Nov-12 4:59 
GeneralRe: Argument with space with file path as value fix Pin
Matthias Schett3-Apr-13 5:18
memberMatthias Schett3-Apr-13 5:18 
QuestionGreat class Pin
WiredEarpzzz10-Jul-11 21:58
memberWiredEarpzzz10-Jul-11 21:58 
GeneralVery Nicely Done!! Pin
raylitalo24-May-11 8:36
memberraylitalo24-May-11 8:36 
GeneralMy vote of 4 Pin
Master_BB2-May-11 22:44
memberMaster_BB2-May-11 22:44 
GeneralRevised code, extension method-ified w/filepath support Pin
PeteM6-Oct-10 13:53
memberPeteM6-Oct-10 13:53 
GeneralRe: Revised code, extension method-ified w/filepath support Pin
tomidery14-Apr-11 5:41
membertomidery14-Apr-11 5:41 
Generalpath as arguments Pin
roman30017824-Feb-10 4:13
memberroman30017824-Feb-10 4:13 
GeneralRe: path as arguments Pin
Tomazaz16-Mar-10 1:10
memberTomazaz16-Mar-10 1:10 
AnswerRe: path as arguments Pin
kaepten10-Jun-10 20:52
memberkaepten10-Jun-10 20:52 
GeneralRe: path as arguments Pin
PeteM6-Oct-10 13:35
memberPeteM6-Oct-10 13:35 
GeneralGreat Tool Pin
ariight27-Oct-09 13:03
memberariight27-Oct-09 13:03 
GeneralMy updated version Pin
Jake Ginnivan26-Jul-09 20:07
memberJake Ginnivan26-Jul-09 20:07 
GeneralRe: My updated version Pin
GriffonRL26-Jul-09 20:34
memberGriffonRL26-Jul-09 20:34 
GeneralInteresting mix of comments! Pin
hughd12-Jul-09 1:40
memberhughd12-Jul-09 1:40 
QuestionWhy to submit buggy code? Pin
Tomazaz30-Jan-09 4:04
memberTomazaz30-Jan-09 4:04 
AnswerRe: Why to submit buggy code? Pin
WiredEarpzzz10-Jul-11 22:03
memberWiredEarpzzz10-Jul-11 22:03 
QuestionThis dude stole your work and then copyrighted it? Pin
mike.griffin@entityspaces.net8-Jan-09 9:35
membermike.griffin@entityspaces.net8-Jan-09 9:35 
AnswerRe: This dude stole your work and then copyrighted it? Pin
mike.griffin@entityspaces.net8-Jan-09 9:37
membermike.griffin@entityspaces.net8-Jan-09 9:37 
GeneralRe: This dude stole your work and then copyrighted it? Pin
GriffonRL8-Jan-09 9:53
memberGriffonRL8-Jan-09 9:53 
AnswerRe: This dude stole your work and then copyrighted it? Pin
GriffonRL8-Jan-09 10:05
memberGriffonRL8-Jan-09 10:05 
GeneralRe: This dude stole your work and then copyrighted it? Pin
mike.griffin@entityspaces.net8-Jan-09 10:53
membermike.griffin@entityspaces.net8-Jan-09 10:53 
GeneralRe: This dude stole your work and then copyrighted it? Pin
GriffonRL8-Jan-09 11:46
memberGriffonRL8-Jan-09 11:46 
GeneralWindows XP anomaly and fix Pin
Todd Smith8-Oct-08 14:15
memberTodd Smith8-Oct-08 14:15 
GeneralNConsoler - another command line parsing library Pin
tihobrazov8-Sep-08 7:54
membertihobrazov8-Sep-08 7:54 
Questionwhat could be better Pin
teetrinker700326-Jun-08 6:32
memberteetrinker700326-Jun-08 6:32 
General;) [modified] Pin
ITMaiO15-May-08 22:44
memberITMaiO15-May-08 22:44 
QuestionLicense Type Pin
bhargav_j25-Mar-08 13:19
memberbhargav_j25-Mar-08 13:19 
QuestionRe: License Type Pin
Peter Kneale24-Aug-08 1:30
memberPeter Kneale24-Aug-08 1:30 
AnswerRe: License Type Pin
GriffonRL24-Aug-08 1:39
memberGriffonRL24-Aug-08 1:39 
QuestionCan you please update the code Pin
JoeBob10127-Sep-07 11:20
memberJoeBob10127-Sep-07 11:20 
GeneralExcellent Pin
Lu Yixiang4-Jun-07 20:15
memberLu Yixiang4-Jun-07 20:15 
GeneralGreat code bud. Pin
mrsnipey3-Jun-07 18:09
membermrsnipey3-Jun-07 18:09 
GeneralThanks for this code! Pin
patiman21-May-07 4:47
memberpatiman21-May-07 4:47 
JokeHurray for the French Pin
Pinx11-Apr-07 5:03
memberPinx11-Apr-07 5:03 
GeneralThanks for the code Pin
Ian Quigley7-Mar-07 2:04
memberIan Quigley7-Mar-07 2:04 
GeneralThanks for the code Pin
j1mcmahon8-Jan-07 14:08
memberj1mcmahon8-Jan-07 14:08 
GeneralDoesn't work with space separator Pin
R. Ian Lee23-Aug-06 12:12
memberR. Ian Lee23-Aug-06 12:12 
GeneralRe: Doesn't work with space separator Pin
GriffonRL24-Aug-06 1:16
memberGriffonRL24-Aug-06 1:16 
GeneralRe: Doesn't work with space separator Pin
GriffonRL24-Aug-06 1:21
memberGriffonRL24-Aug-06 1:21 
GeneralRe: Doesn't work with space separator Pin
Knuddlbaer13-Mar-08 4:13
memberKnuddlbaer13-Mar-08 4:13 
GeneralSeems to choke on parameters containing a file name / path Pin
Marc Scheuner15-Aug-06 1:46
memberMarc Scheuner15-Aug-06 1:46 
GeneralRe: Seems to choke on parameters containing a file name / path Pin
GriffonRL15-Aug-06 16:05
memberGriffonRL15-Aug-06 16:05 
AnswerRe: Seems to choke on parameters containing a file name / path Pin
Dave Felcan18-Sep-06 17:49
memberDave Felcan18-Sep-06 17:49 
GeneralRe: Seems to choke on parameters containing a file name / path Pin
marlberg12319-Jul-07 10:27
membermarlberg12319-Jul-07 10:27 
GeneralRe: Seems to choke on parameters containing a file name / path Pin
mr.jawright@gmail.com2-Nov-07 11:15
membermr.jawright@gmail.com2-Nov-07 11:15 
GeneralRe: Seems to choke on parameters containing a file name / path Pin
j_wright2-Nov-07 12:20
memberj_wright2-Nov-07 12:20 
GeneralAnother Version Pin
raymond7725-Jul-06 6:41
memberraymond7725-Jul-06 6:41 
GeneralRe: Another Version Pin
GriffonRL25-Jul-06 11:32
memberGriffonRL25-Jul-06 11:32 
Generalc++ version Pin
Aaron Sulwer12-Jul-06 6:07
memberAaron Sulwer12-Jul-06 6:07 
GeneralRe: c++ version Pin
GriffonRL25-Jul-06 11:40
memberGriffonRL25-Jul-06 11:40 
AnswerC++/CLI version Pin
semmel719-Jan-07 9:36
membersemmel719-Jan-07 9:36 
GeneralBUG: quotes in ApplicationName and string arguments Pin
ChrisHubbard7-Jul-06 7:57
memberChrisHubbard7-Jul-06 7:57 
GeneralRe: BUG: quotes in ApplicationName and string arguments Pin
GriffonRL25-Jul-06 11:41
memberGriffonRL25-Jul-06 11:41 
GeneralThanks Pin
ChrisLee13-Jul-06 4:58
memberChrisLee13-Jul-06 4:58 
Generalmy version Pin
gunnarD24-Jun-06 6:49
membergunnarD24-Jun-06 6:49 
GeneralRe: my version Pin
GriffonRL25-Jul-06 11:51
memberGriffonRL25-Jul-06 11:51 
GeneralRe: my version Pin
rastalin24-Oct-07 11:53
memberrastalin24-Oct-07 11:53 
GeneralRe: my version Pin
rastalin25-Oct-07 5:42
memberrastalin25-Oct-07 5:42 
GeneralRe: my version Pin
gunnarD25-Oct-07 15:00
membergunnarD25-Oct-07 15:00 
Generalnice work! Pin
monkeyWithAKeyboard9-Jun-06 5:50
membermonkeyWithAKeyboard9-Jun-06 5:50 
GeneralRe: nice work! Pin
GriffonRL9-Jun-06 17:06
memberGriffonRL9-Jun-06 17:06 
GeneralUrgent Help Pin
Deric Davis17-May-06 11:51
memberDeric Davis17-May-06 11:51 
GeneralRe: Urgent Help Pin
GriffonRL17-May-06 15:16
memberGriffonRL17-May-06 15:16 
GeneralRe: Urgent Help Pin
Deric Davis18-May-06 6:10
memberDeric Davis18-May-06 6:10 
GeneralRe: Urgent Help Pin
GriffonRL18-May-06 18:21
memberGriffonRL18-May-06 18:21 
JokeThank You. I'd recommend to others... Pin
Christopher Scholten6-Apr-06 8:24
memberChristopher Scholten6-Apr-06 8:24 
GeneralRe: Thank You. I'd recommend to others... Pin
GriffonRL6-Apr-06 11:02
memberGriffonRL6-Apr-06 11:02 
GeneralAdded support to handel unnamed arguments Pin
Anders Bjerin12-Feb-06 0:31
memberAnders Bjerin12-Feb-06 0:31 
GeneralRe: Added support to handel unnamed arguments Pin
GriffonRL12-Feb-06 1:09
memberGriffonRL12-Feb-06 1:09 
GeneralRe: Added support to handel unnamed arguments Pin
Anders Bjerin12-Feb-06 1:21
memberAnders Bjerin12-Feb-06 1:21 
GeneralRe: Added support to handel unnamed arguments Pin
Gunn31715-Feb-06 11:46
memberGunn31715-Feb-06 11:46 
GeneralRe: Added support to handel unnamed arguments Pin
Matthias833-Sep-06 2:13
memberMatthias833-Sep-06 2:13 
GeneralRe: Added support to handel unnamed arguments Pin
pbarrette14-Jul-06 9:24
memberpbarrette14-Jul-06 9:24 
QuestionIs argument case sensitive? Pin
Hardy1-Dec-05 7:04
memberHardy1-Dec-05 7:04 
AnswerRe: Is argument case sensitive? Pin
Anders Bjerin11-Feb-06 23:10
memberAnders Bjerin11-Feb-06 23:10 
AnswerRe: Is argument case sensitive? Pin
Eric Bowden27-Jun-06 12:19
memberEric Bowden27-Jun-06 12:19 
GeneralGreat Work! Pin
Mark (Code6) Belles7-Mar-05 19:43
memberMark (Code6) Belles7-Mar-05 19:43 
GeneralRe: Great Work! Pin
GriffonRL12-Feb-06 1:03
memberGriffonRL12-Feb-06 1:03 
Questiongpl'd? Pin
Anonymous3-Feb-04 22:01
sussAnonymous3-Feb-04 22:01 
AnswerRe: gpl'd? Pin
GriffonRL12-Feb-06 1:12
memberGriffonRL12-Feb-06 1:12 
GeneralVisual Basic version Pin
Eric Marcon7-Aug-03 5:31
memberEric Marcon7-Aug-03 5:31 
GeneralRe: Visual Basic version Pin
GriffonRL7-Aug-03 5:51
memberGriffonRL7-Aug-03 5:51 
GeneralAlternative solutions Pin
Roman Kuzmin20-Jul-03 17:03
memberRoman Kuzmin20-Jul-03 17:03 
GeneralRe: An alternative solution Pin
GriffonRL20-Jul-03 23:34
memberGriffonRL20-Jul-03 23:34 
GeneralThe article has been updated Pin
Roman Kuzmin21-Jul-03 4:55
memberRoman Kuzmin21-Jul-03 4:55 
GeneralOne more solution Pin
Roman Kuzmin8-Aug-03 10:01
memberRoman Kuzmin8-Aug-03 10:01 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.160208.1 | Last Updated 6 Nov 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid