2

What is the appropriate method to read arguments from command line? I've read of using strings args[] but I can't come to grasp the concept of how to do it properly.

Example Commands:

/animal dog -c white -s medium

/car civic -c green -y 1999

What would be the appropriate manner to read,

  1. /thecommand

  2. all the other -letter arguments

for easier manipulation? Or is there a cleaner way in general to do this than using args? Still not sure as to how args is used.

    static void Main(string[] args)
    {

        Console.WriteLine("Welcome To The Application");

        Console.Write("Program> "); // Expecting something such as: /animal dog -c brown -s medium
        string sInput = Console.ReadLine();

        // What would be an appropriate method to read 1. /thecommand then based on the command
        // maybe using switch, expect the arguments like -c brown -s medium or -c green -y 1999
        // and display them into the console?


        // if /animal is detected, display what would be:
        // Console.WriteLine("Animal: dog");
        // Console.WriteLine("Color: brown");
        // Console.WriteLine("Size: medium");

        // if /car is detected, display what would be:
        // Console.WriteLine("Car: civic");
        // Console.WriteLine("Color: green");
        // Console.WriteLine("Year: 1999");

    }
  • Also refer to the following post on this topic which has more answers: http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c – Qwerty Nov 09 '09 at 02:56

3 Answers3

1

It depends on the complexity. If you only have a few options, a simple for/switch would suffice. If the options are complex, you might want a class that allows you to map "-c" to "Color" etc. Examples (just the first 2 from google; not a specific recommendation) of this second approach are here and here.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

If you're looking for a pretty nice command line parser, you should try out the command line parser library at CodePlex -- http://www.codeplex.com/commandline It's pretty simple, comes with unit tests and covers the major use cases.

Another option is NDesk - http://www.ndesk.org/Options - which is supposed to be the successor to the command line parsing utilities in Mono.

Anteru
  • 19,042
  • 12
  • 77
  • 121
0

I see you've posted a number of questions in the console app range of topics. To answer this question and potentially any others you have, you may want to look at this library dedicated to writing console app's. It includes command line parsers

NConsoler

Logicalmind
  • 3,436
  • 1
  • 16
  • 9