Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / C#
Article

Extracts Arguments Passed by User to a Console Application

Rate me:
Please Sign up or sign in to vote.
2.82/5 (7 votes)
28 May 2006CPOL2 min read 86.1K   1.7K   16   4
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"

Image 1

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

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

Now instantiate the CmdArgsExtractor class, where:

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

Option 2

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

Image 2

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

C#
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?

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

2. Did the User Supply Valid Prefixes?

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

Step 4 - Extracting the Arguments

The class implements three methods:

C#
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.

C#
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"

C#
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

C#
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

License

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


Written By
Web Developer
United Kingdom United Kingdom
Alex B. Clarke is a professioinal software developer specialising in .Net, C#, Asp.Net, SQL, ADSI, CDO, and other technolgies. He writes applications that automate business processes.

Comments and Discussions

 
GeneralValid prefix vs Required Prefix Pin
James Cooke26-May-10 16:55
James Cooke26-May-10 16:55 
GeneralConcerning Source Code Pin
lew2630-May-06 0:58
lew2630-May-06 0:58 
GeneralRe: Concerning Source Code Pin
Alex B. Clarke30-May-06 2:07
Alex B. Clarke30-May-06 2:07 
Thanks for pointing this out, my mistake.
All should be fixed now.

Alex B. Clarke
GeneralRe: Concerning Source Code Pin
lew2630-May-06 2:31
lew2630-May-06 2:31 

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.