C # Command Line Parameter Parsing class and use instance

Source: Internet
Author: User

Http://blog.csdn.net/jackxinxu2100/article/details/6642694

 

It is critical to parse command line parameters when writing command line programs, the following introduces a command line Parameter Parsing class in codeproject and describes how to use it to describe the process of parsing C # command line parameters.

First, let's look at the Parameter Parsing class, which is divided into CommandLine and commandargs. The former is responsible for parsing, the latter is responsible for result encapsulation, And the parsed results are divided into three types: Key/value type corresponding to a = B, -Option and option value corresponding to a B (can be omitted, and the value is converted to true), and The param type corresponding to individual AAA.

//---------------------------------------------------------------------

/// <Summary>

/// Contains the parsed command line arguments. This consists of two

/// Lists, one of argument pairs, and one of stand-alone arguments.

/// </Summary>

Public class commandargs

{

//---------------------------------------------------------------------

/// <Summary>

/// Returns the dictionary of argument/value pairs.

/// </Summary>

Public dictionary <string, string> argpairs

{

Get {return margpairs ;}

}

Dictionary <string, string> margpairs = new dictionary <string, string> ();

//---------------------------------------------------------------------

/// <Summary>

/// Returns the list of stand-alone parameters.

/// </Summary>

Public list <string> Params

{

Get {return mparams ;}

}

List <string> mparams = new list <string> ();

}

//---------------------------------------------------------------------

/// <Summary>

/// Implements command line Parsing

/// </Summary>

Public class CommandLine

{

//---------------------------------------------------------------------

/// <Summary>

/// Parses the passed command line arguments and returns the result

/// In a commandargs object.

/// </Summary>

/// The command line is assumed to be in the format:

///

/// Cmd [Param] [[-| -- | \] & lt; arg & gt; [[=] & lt; Value & gt;] [Param]

///

/// Basically, stand-alone parameters can appear anywhere on the command line.

/// Arguments are defined as key/value pairs. The argument key must begin

// With a'-',' -- ', or' \ '. Between the argument and the value must be

/// Least one space or a single '='. Extra spaces are ignored. Arguments may

/// Be followed by a value or, if no value supplied, the string 'true' is used.

/// You must enclose argument values in quotes if they contain a space, otherwise

/// They will not parse correctly.

///

/// Example command lines are:

///

/// Cmd first-O outfile.txt -- compile second \ errorspolicerrors.txt third fourth -- test = "the value" th

///

/// <Param name = "ARGs"> array of command line arguments </param>

/// <Returns> commandargs object containing the parsed command line </returns>

Public static commandargs parse (string [] ARGs)

{

Char [] kequal = new char [] {'= '};

Char [] kargstart = new char [] {'-', '\'};

Commandargs CA = new commandargs ();

Int II =-1;

String token = nexttoken (ARGs, ref II );

While (Token! = NULL)

{

If (isarg (token ))

{

String Arg = token. trimstart (kargstart). trimend (kequal );

String value = NULL;

If (Arg. Contains ("= "))

{

// Arg was specified with an '= 'sign, so we need

// To split the string into the Arg and value, but only

// If there is no space between the '=' and the Arg and value.

String [] r = Arg. Split (kequal, 2 );

If (R. Length = 2 & R [1]! = String. Empty)

{

Arg = R [0];

Value = R [1];

}

}

While (value = NULL)

{

String next = nexttoken (ARGs, ref II );

If (next! = NULL)

{

If (isarg (next ))

{

// Push the token back onto the stack so

// It gets picked up on next pass as an ARG

II --;

Value = "true ";

}

Else if (next! = "= ")

{

// Save the value (trimming any '=' from the start)

Value = next. trimstart (kequal );

}

}

}

// Save the pair

CA. argpairs. Add (ARG, value );

}

Else if (Token! = String. Empty)

{

// This is a stand-alone parameter.

CA. Params. Add (token );

}

Token = nexttoken (ARGs, ref II );

}

Return CA;

}

//---------------------------------------------------------------------

/// <Summary>

/// Returns true if the passed string is an argument (starts

// '-', '--', Or '\'.)

/// </Summary>

/// <Param name = "Arg"> the string token to test </param>

/// <Returns> true if the passed string is an argument, else false if a parameter </returns>

Static bool isarg (string Arg)

{

Return (Arg. startswith ("-") | arg. startswith ("\\"));

}

//---------------------------------------------------------------------

/// <Summary>

/// Returns the Next string token in the argument list

/// </Summary>

/// <Param name = "ARGs"> List of string tokens </param>

/// <Param name = "II"> index of the current token in the array </param>

/// <Returns> The Next string token, or null if no more tokens in array </returns>

Static string nexttoken (string [] ARGs, ref int II)

{

II ++; // move to next token

While (II <args. length)

{

String cur = ARGs [II]. Trim ();

If (cur! = String. Empty)

{

// Found valid token

Return cur;

}

II ++;

}

// Failed to get another token

Return NULL;

}

}

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------

The following uses a command line program to explain how to call the above parsing class and parse the specific command line. The following is the calling code.

Static void main (string [] ARGs)

{

 

Commandargs commandarg = CommandLine. parse (ARGs );

List <string> lparams = commandarg. Params;

For (INT I = 0; I <lparams. Count; I ++)

{

String commandargstring = commandarg. Params [I];

System. Console. writeline (commandargstring );

}

Dictionary <string, string> argpairs = commandarg. argpairs;

List <string> keys = argpairs. Keys. tolist ();

For (INT I = 0; I <keys. Count; I ++)

{

String strkey = keys [I];

String strvalue = argpairs [strkey];

System. Console. writeline ("key/value:" + strkey + "/" + strvalue );

}

}

Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------

Enter the command line parameter "-CC-dd ee ff-this a-that B CCC = fff BBB = Rrrr" during the test. Check the final parsing result by yourself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.