C#命令行参数解析类以及使用实例

编写命令行程序时如何进行命令行参数解析至关重要,下面将引用codeproject里面的一个命令行参数解析类并阐述如何使用来说明C#命令行参数解析的过程。

先看参数解析类,分为CommandLine类以及CommandArgs类,前者负责解析,后者负责结果封装,解析的结果分为三类:即 a=b 对应的key/value类型,-a b 对应的option与option value(可省略,值即转为true),以及单独的aaa所对应的param类型。

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

///

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

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

///

public class CommandArgs

{

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

///

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

///

public Dictionary<string, string> ArgPairs

{

get { return mArgPairs; }

}

Dictionary<string, string> mArgPairs = new Dictionary<string, string>();

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

///

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

///

public List<string> Params

{

get { return mParams; }

}

List<string> mParams = new List<string>();

}

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

///

/// Implements command line parsing

///

public class CommandLine

{

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

///

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

/// in a CommandArgs object.

///

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

///

/// CMD [param] [[-|--|\]<arg>[[=]<value>]] [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 at

/// 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 \errors=errors.txt third fourth --test = "the value" fifth

///

/// array of command line arguments

/// CommandArgs object containing the parsed command line

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;

}

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

///

/// Returns True if the passed string is an argument (starts with

/// '-', '--', or '\'.)

///

/// the string token to test

/// true if the passed string is an argument, else false if a parameter

static bool IsArg(string arg)

{

return (arg.StartsWith("-") || arg.StartsWith("\\"));

}

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

///

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

///

/// list of string tokens

/// index of the current token in the array

/// the next string token, or null if no more tokens in array

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;

}

}

---------------------------------------------------------------------------------------------------------------------------------------------

下面使用一个命令行程序来说明如何调用上述解析类,对具体的命令行解析,如下是调用代码。

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);

}

}

----------------------------------------------------------------------------------------------------------------------------------------------------

测试时输入命令行参数“ -cc -dd ee ff -this a -that b ccc=fff bbb=rrrr ”,最后的解析结果请大家自己查看一下。

你可能感兴趣的:(Vs.NET,平台,c#,string,token,command,null,dictionary)