65.9K
CodeProject is changing. Read more.
Home

Extracts Arguments Passed by User to a Console Application

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.82/5 (7 votes)

May 28, 2006

CPOL

2 min read

viewsIcon

86548

downloadIcon

1708

This article shows how to extract arguments passed by user to a console application

CmdArgsExtractor

There are many ways of getting the values of arguments from Main(string[] args). When you write a console type application that expects a user to pass some parameters, for example...

copyFile /source:c:\test.txt /destination:g:\new_test.txt

... you'll need to grab:

  • c:\test.txt as the source file, and
  • g:\new_test.txt as destination

CmdArgsExtrator.dll can help you achieve this in just a few lines of code.

Step 1 - Preparation

  1. Download and extract CmdArgsExtractor.dll
  2. Open an existing or create a new "Console Application" project
  3. Add a reference to CmdArgsExtractor.dll

Step 2 - Using Constructors

Option 1

Let's say, we expect a user to pass arguments in the following format:
"/a:alpha", "/b:beta", "/t:theta"

First, declare your valid prefixes.
For the above example, you'll code this as follows:

   string[] prefixes = new string[] { "/a:", "/b:", "/t:" };

Now instantiate the CmdArgsExtractor class, where:

  • '/' is the argument separator, and
  • ':' is the argument value separator
   CmdArgExtractor cae = new CmdArgExtractor(prefixes, '/', ':');

Option 2

If your program takes arguments in the following format...

... then you would instantiate the class in this way:

   CmdArgExtractor cae = new CmdArgExtractor('/');

Now you are ready to use the class methods.

Step 3 - Validation

There are a couple of things you may want to check before extracting arguments specified by the user.

1. Do We Have Any Arguments At All?

   if ((args.Length != 0) && (args[0].Contains("?"))) {
      // show syntax
      return;
   }

2. Did the User Supply Valid Prefixes?

   if (!cae.ValidArgsPrefixes(args)) {
      // ... show syntax
      return;
   }

Step 4 - Extracting the Arguments

The class implements three methods:

GetArgValues(string[] args)

This returns an array of argument values, and can be used when arguments are expected to be in either "/alpha /beta" or "/a:alpha /b:beta" format.

GetArgsTwoDimArray(string[] args)

This is useful when the arguments are in the format "/a:alpha /b:beta" and you want to code different options for each argument value.
It returns a two-dimensional array where, the first dimension elements are "qualifiers" - for the above example, they will be "a" and "b", and the second dimension elements are the argument values - "alpha" and "beta"

GetArgValuesSimple(string[] args)

This is the same as GetArgValues but is used when you expect arguments in the format "/alpha /beta". This method again will return an array containing argument values, e.g. "alpha" and "beta".

Example

using System;

namespace Xealcom.Utils {

   /// <summary>
   /// This just a simple demo test app.
   /// </summary>
   class Program {
      /// <summary>
      /// Expects 3 arguments in the format '/arg:param'
      /// </summary>
      static void Main(string[] args) {

         // assume that this is what user passed as parameters
         // this line is only for demo purposes
         args = new string[] { "/a:alpha", "/b:beta", "/t:theta" };

         // validate the number of args if necessary
         if (args.Length != 3) {
            // show syntax
            return;
         }

         // Check if user is asking for help with the syntax
         if ((args.Length != 0) && (args[0].Contains("?"))) {
            // show syntax
            return;
         }

         // instantiate the CmdArgsExtrator
         // this is what we expect as args prefixes
         string[] prefixes = new string[] { "/a:", "/b:", "/t:" };
         CmdArgExtractor cae = new CmdArgExtractor(prefixes, '/', ':');

         // validate prefixes
         if (!cae.ValidArgsPrefixes(args)) {
            // ... show syntax perhaps
            return;
         }

         // Get only the values of args in one-dim array
         // this method is useful if you expect arguments without 
         // args value separator like this "/alpha /beta /theta"
         string[] myArgs = cae.GetArgValues(args);
         Console.WriteLine("---- GetArgValues output ----");
         foreach (string arg in myArgs) {
            Console.WriteLine("{0}",arg);
         }

         // Get 2-dim array where,
         // 1st dim - are args qualifiers, e.g. "a" in "/a:alpha"
         // 2nd dim - are the values, e.g. "alpha" in "/a:alpha"
         string[,] my2dArr = cae.GetArgsTwoDimArray(args);
         Console.WriteLine("---- GetArgsTwoDimArray output ----");
         for (int i = 0; i < my2dArr.GetLength(1); i++) {
            Console.WriteLine("Arg qualifier: {0}\tValue: {1}",
                               my2dArr[0, i], my2dArr[1, i]);
         }
      }
   }///class
}///namespace

Hope this helps.

History

  • 28th May, 2006: Initial post