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

 

  /// <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

  {

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

 

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

 

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

 

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

 

      /// <summary>

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

      /// </summary>

      public Dictionary<string, string> ArgPairs

      {

          get { return this.mArgPairs; }

      }

 

      /// <summary>

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

      /// </summary>

      public List<string> Params

      {

          get { return this.mParams; }

      }

  }

 

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

 

  /// <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 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

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

      /// <returns> CommandArgs object containing the parsed command line </returns>

      public static CommandArgs Parse(string[] args)

      {

          var kEqual = new char[] {'='};

 

          var kArgStart = new char[] {'-', '\\'};

 

          var ca = new CommandArgs();

 

          var ii = -1;

 

          var token = NextToken(args, ref ii);

 

          while (token != null)

          {

              if (IsArg(token))

              {

                  var 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.

 

                      var r = arg.Split(kEqual, 2);

 

                      if (r.Length == 2 && r[1] != string.Empty)

                      {

                          arg = r[0];

 

                          value = r[1];

                      }

                  }

 

                  while (value == null)

                  {

                      var 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 with 

      ///   '-', '--', 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>

      private 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>

      private static string NextToken(string[] args, ref int ii)

      {

          ii++; // move to next token

 

          while (ii < args.Length)

          {

              var cur = args[ii].Trim();

 

              if (cur != string.Empty)

              {

                  // found valid token

 

                  return cur;

              }

 

              ii++;

          }

 

          // failed to get another token

 

          return null;

      }

  }

控制台解析命行C#的更多相关文章

  1. 使用ACE_Get_Opt解析命令行

    当我们用C++开发一些C++控制台小工具时,会需要一些用户输入的参数来决定程序如何工作和执行,而用户输入参数的方式大部分都是采用命令行参数的方式. 比如上一篇文章 玩转Windows服务系列--命令行 ...

  2. Chrome控制台输入多行js

    Chrome控制台输入多行js 分类: chrome2013-09-08 09:40 342人阅读 评论(0) 收藏 举报 控制台 Chrome控制台中回车默认是执行,要想输入换行,应按Enter+S ...

  3. boost之program_options库,解析命令行参数、读取配置文件

    一.命令行解析 tprogram_options解析命令行参数示例代码: #include <iostream> using namespace std; #include <boo ...

  4. ACE_Get_Opt解析命令行

    ACE_Get_Opt是一种解析命令行参数选项的迭代器. 1:构造方法 ACE_Get_Opt需要引用头文件,#include "ace/Get_Opt.h". ACE_Get_O ...

  5. shell解析命令行的过程以及eval命令

    本文说明的是一条linux命令在执行时大致要经过哪些过程?以及这些过程的大致顺序. 1.1 shell解析命令行 shell读取和执行命令时的大致操作过程如下图: 以执行以下命令为例: echo -e ...

  6. optparse模块解析命令行参数的说明及优化

    一.关于解析命令行参数的方法 关于“解析命令行参数”的方法我们一般都会用到sys.argv跟optparse模块.关于sys.argv,网上有一篇非常优秀的博客已经介绍的很详细了,大家可以去这里参考: ...

  7. python解析命令行参数

    常常需要解析命令行参数,经常忘记,好烦,总结下来吧. 1.Python 中也可以所用 sys 的 sys.argv 来获取命令行参数: sys.argv 是命令行参数列表 参数个数:len(sys.a ...

  8. C#/.NET 使用 CommandLineParser 来标准化地解析命令行

    CommandLineParser 是一款用于解析命令行参数的 NuGet 包.你只需要关注你的业务,而命令行解析只需要极少量的配置代码. 本文将介绍如何使用 CommandLineParser 高效 ...

  9. 使用 Apache Commons CLI 解析命令行参数示例

    很好的输入参数解析方法 ,转载记录下 转载在: https://www.cnblogs.com/onmyway20xx/p/7346709.html Apache Commons CLI 简介 Apa ...

随机推荐

  1. 优于jdbc的mybatis框架入门

    1.什么是mybatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索. MyB ...

  2. zookeeper java api(使用java代码操作zookeeper)

    1 导入相关的pom依赖 <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId&g ...

  3. SolrCloud中的文件与Collection管理

    转载请出自出处:http://eksliang.iteye.com/blog/2124078 http://eksliang.iteye.com/ 一.内嵌启动SolrCloud时端口默认分配 当 S ...

  4. git配置多用户多平台

    在Git使用中经常会碰到多用户问题,例如:你在公司里有一个git账户,在github上有一个账户,并且你想在一台电脑上同时对这两个git账户进行操作,此时就需要进行git多用户配置. 首先配置不同的S ...

  5. 07-Location之正则匹配

    大网站专门有自己的图片服务器,起码也得单独放一个目录里面. 淘宝网有些图片开启了防盗链(即使是小图片,也不让你下载,真小气).163新闻可以下载. 用正则匹配uri中的image,就是说你的uri中到 ...

  6. 【HDU5861】Road

    题意 有n个村庄排成一排,有n-1条路将他们连在一起.每条路开放一天都会花费一定数量的钱.你可以选择打开或者关上任意条路在任意一天,但是每条路只能打开和关闭一次.我们知道m天的运输计划.每天都有一辆马 ...

  7. quilljs 一款简单轻量的富文本编辑器(适合移动端)

    quilljs入门使用教程: quill.js是一款强大的现代富文本编辑器插件.该富文本编辑器插件支持所有的现代浏览器.平板电脑和手机.它提供了文本编辑器的所有功能,并为开发者提供大量的配置参数和方法 ...

  8. vue.js的一些模板指令简述

    1.模板指令都是写在<template></template>html里面   v-text : value是什么就显示什么,如果value里面有html的标签,也会直接显示出 ...

  9. 第07章-Spring MVC 的高级技术

    Spring MVC 的高级技术 1. Spring MVC配置的替代方案 1.1 自定义DispatcherServlet配置 AbstractAnnotationConfigDispatcherS ...

  10. Deep Visual-Semantic Alignments for Generating Image Descriptions(深度视觉-语义对应对于生成图像描述)

    https://cs.stanford.edu/people/karpathy/deepimagesent/ Abstract We present a model that generates na ...