c# - 读取命令行args及其相关值

时间:2015-06-01 09:22:53

标签: c# command-line console-application args command-line-parsing

只是想知道是否有办法在控制台应用中读取命令行中的值。我可以很容易地阅读命令行,但似乎无法找到有关从命令行获取值的任何信息。

例如(args):

aTest = 5; bTest = 13;

是否有办法在arg aTest中读取它与int 5的关联...?

谢谢:)

2 个答案:

答案 0 :(得分:2)

我已经为我写了一个帮助方法,它提取了swtich的值或返回(如果存在或不存在) - 这对你有帮助。

/// <summary>
/// If the arguments are in the format /member=value
/// Than this function returns the value by the given membername (!casesensitive) (pass membername without '/')
/// If the member is a switch without a value and the switch is preset the given ArgName will be returned, so if switch is presetargname means true..
/// </summary>
/// <param name="args">Console-Arg-Array</param>
/// <param name="ArgName">Case insensitive argname without /</param>
/// <returns></returns>
private static string getArgValue(string[] args, string ArgName)
{
    var singleFound = args.Where(w => w.ToLower() == "/" + ArgName.ToLower()).FirstOrDefault();
    if (singleFound != null)
        return ArgName;


    var arg = args.Where(w => w.ToLower().StartsWith("/" + ArgName.ToLower() + "=")).FirstOrDefault();
    if (arg == null)
        return null;
    else
        return arg.Split('=')[1];
}

示例:

static void Main(string[] args)
 {
    var modeSwitchValue = getArgValue(args, "mode");
    if (modeSwitchValue == null)
    {
        //Argument not present
        return;
    }
    else
    { 
        //do something
    }
  }

答案 1 :(得分:0)

这可以找到你提供的输入:

var args = "aTest = 5; bTest = 13;";

var values =
    args
        .Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(x => x.Trim().Split('=').Select(y => y.Trim()).ToArray())
        .ToDictionary(x => x[0], x => int.Parse(x[1]));

我得到了这个结果:

result