Alex Rivera | Logout

How can I obtain the named arguments from a console application in the form of a Dictionary<string,string>?

Asked 2012-07-11T09:51:02.553
34

I have a console application called MyTool.exe

What is the simplest way to collect the named arguments passed to this console applicaiton and then to put them in a Dictionarty<string, string>() which will have the argument name as the key and the value as the argument?

for example:

MyTool foo=123432 bar=Alora barFoo=45.9

I should be able to obtain a dictionary which will be:

MyArguments["foo"]=123432 
MyArguments["bar"]="Alora"
MyArguments["barFoo"]="45.9"
Edit
Report

1 Answer

16

Here's how this can be done in the most simple way:

    static void Main(string[] args)
    {
        var arguments = new Dictionary<string, string>();

        foreach (string argument in args)
        {
            string[] splitted = argument.Split('=');

            if (splitted.Length == 2)
            {
                arguments[splitted[0]] = splitted[1];
            }
        }
    }

Note that:

  • Argument names are case sensitive
  • Providing the same argument name more than once does not produce an error
  • No spaces are allowed
  • One = sign must be used
answered 2012-07-13T16:59:54.280

Your Answer