如何获取命令行参数并将它们放入变量中?

我正在尝试申请。 有人可以帮助我如何获取命令行参数并将它们放入变量/字符串。 我需要在C#上执行此操作,它必须是5个参数。

第一个参数需要放入Title变量。 第二个参数需要放入Line1变量。 第三个参数需要放入Line2变量。 第四个参数需要放入Line3变量。 第五个参数需要放入Line4变量。

坦克你的帮助!

编辑:

我需要将其添加到Windows窗体应用程序中。

您可以通过以下两种方式之一来完成。

第一种方法是使用string[] args并将其从Main传递给你的Form ,如下所示:

 // Program.cs namespace MyNamespace { static class Program { ///  /// The main entry point for the application. ///  [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyForm(args)); } } } 

然后在MyForm.cs执行以下操作:

 // MyForm.cs namespace MyNamespace { public partial class MyForm : Form { string Title, Line1, Line2, Line3, Line4; public MyForm(string[] args) { if (args.Length == 5) { Title = args[0]; Line1 = args[1]; Line2 = args[2]; Line3 = args[3]; Line4 = args[4]; } } } } 

另一种方法是使用Environment.GetCommandLineArgs() ,如下所示:

 // MyForm.cs namespace MyNamespace { public partial class MyForm : Form { string Title, Line1, Line2, Line3, Line4; public MyForm() { string[] args = Environment.GetCommandLineArgs(); if (args.Length == 6) { // note that args[0] is the path of the executable Title = args[1]; Line1 = args[2]; Line2 = args[3]; Line3 = args[4]; Line4 = args[5]; } } } } 

如果没有string[] args ,你只需要将Program.cs保留原来的样子。

命令行参数在args数组中找到

 public static void Main(string[] args) { // The Length property is used to obtain the length of the array. // Notice that Length is a read-only property: Console.WriteLine("Number of command line parameters = {0}", args.Length); for(int i = 0; i < args.Length; i++) { Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]); } } 

来源http://msdn.microsoft.com/en-us/library/aa288457(v=vs.71).aspx

考虑使用库来为您完成所有这些解析。 我在CodePlex上使用Command Line Parser库取得了成功:

http://commandline.codeplex.com/

您可以使用Nuget获取此库:

 Install-Package CommandLineParser 

以下是一个示例用法:

 // Define a class to receive parsed values class Options { [Option('r', "read", Required = true, HelpText = "Input file to be processed.")] public string InputFile { get; set; } [Option('v', "verbose", DefaultValue = true, HelpText = "Prints all messages to standard output.")] public bool Verbose { 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 if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile); } }