C#从命令行读取多个参数

本文关键字:参数 读取 命令行 | 更新日期: 2023-09-27 18:02:57

如果我想这样执行,在其他语言中很常见:program.exe-u user-p password

如何在C#((中对此进行编码?

C#从命令行读取多个参数

static void Main(string[] args)
{
}

并且CCD_ 1数组将包含参数列表。

如何使用NDesk.Options:解决此问题

static void Main(string[] args)
{
    // Loading via the command line; parse command line args
    string username = string.Empty;
    string password = string.Empty;
    OptionSet CmdParser = new OptionSet
    {
        { "u|username=", "Username",  u => username = u },
        { "p|password=", "Password",  p => password = p }
    };
    try
    {
        // Loading via the command line; parse command line arguments
        List<string> unknownArgs = CmdParser.Parse(args);
        if (unknownArgs.Count > 1)
        {
            Console.Write("Unrecognised argument in: '{0}'", string.Join(" ", unknownArgs));
        }
    }
    catch (OptionException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

对于更面向功能的方法,您可以安装最新版本的命令行解析器

Install-Package CommandLineParser -pre

定义一个选项类

 class Options
 {
     [Option('u', "user", Required = true, HelpText = "username")]
     public string UserName { get; set; }
     [Option('p', "password", Required = true, HelpText = "password")]
     public string Password { get; set; }
     [Value(0)]
     public IEnumerable<string> StringSequence { get; set; }
 }

并解析命令行

class Program
{
    static int Main(string[] args)
    {
        var parser = new Parser(settings =>
        {
            settings.CaseSensitive = false;
            settings.HelpWriter = Console.Error;
            settings.IgnoreUnknownArguments = false;
        });
        var result = parser.ParseArguments<Options>(args);
        var exitCode = result
.MapResult(
  options =>
  {
      if (options.StringSequence.Count() > 0)
      {
          Console.WriteLine("unbound params: " +
          String.Join(",", options.StringSequence)
          );
          return 1;
      }
      Console.WriteLine("Hi " + options.UserName + ", your password is");
      Console.WriteLine(options.Password);
      return 0;
  },
  errors =>
  {
      Console.WriteLine(
          String.Join(",",
          errors.Select(x => x.ToString())
          )
          );
      return 1;
  });
        return exitCode;
    }
}
public static void Main(string[] args)
{
    var user = args[1];
    var password = args[3];
}

这是一个乏力的实现,和其他已经回复的实现一样,我建议您使用nuget包来完成这项工作。

以下是我以前使用过的2个(我没有测试这些实现,但它们应该能让你达到80%(:

http://www.ndesk.org/Options

static void Main(string[] args)
       {
              string user = string.Empty;
              string password = string.Empty;
              int verbose = 0;
              var p = new OptionSet () {
               { "u|user",      v => user = v },
               { "p|password",  v => password = v },
              };
              List<string> extra = p.Parse (args);
              Console.WriteLine($"user:{user}");
       }

https://commandline.codeplex.com/

// Define a class to receive parsed values
class Options {
  [Option('u', "user", Required=true, HelpText="username")]
  public string UserName { get; set; }     
  [Option('p', "password", Required=true, HelpText="password")]
  public string Password { get; set; }
  [ParserState]
  public IParserState LastParserState { get; set; }
  [HelpOption]
  public string GetUsage() {
    return HelpText.AutoBuild(this,
      (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
  }
}
// Consume them
static void Main(string[] args) {
  var options = new Options();
  if (CommandLine.Parser.Default.ParseArguments(args, options)) 
  {
         // Values are available here
        Console.WriteLine($"UserName:{options.UserName}");
  }
}