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

时间:2016-08-18 20:42:25

标签: c#

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

如何在C#main()中编写代码?

4 个答案:

答案 0 :(得分:5)

static void Main(string[] args)
{
}

args数组将包含参数列表。

答案 1 :(得分: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);
    }
}

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

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