如何:显示命令行参数(C# 编程指南)

可以通过 Main 的可选参数来访问通过命令行提供给可执行文件的参数。参数以字符串数组的形式提供。数组的每个元素都包含一个参数。参数之间的空白被移除。例如,下面是对一个假想的可执行文件的命令行调用:

命令行输入 传递给 Main 的字符串数组
executable.exe a b c "a""b"“c”
executable.exe one two "one""two"
executable.exe "one two" three "one two""three"
注意
在 Visual Studio 中运行应用程序时,可以在“项目设计器”->“调试”页中指定命令行参数。

本示例显示了传递给命令行应用程序的命令行参数。显示的输出对应于上表中的第一项。

class CommandLine
{
    static void Main(string[] args)
    {
        // The Length property provides the number of array elements
        System.Console.WriteLine("parameter count = {0}", args.Length);

        for (int i = 0; i < args.Length; i++)
        {
            System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }
    }
}
/* Output (assumes 3 cmd line args):
    parameter count = 3
    Arg[0] = [a]
    Arg[1] = [b]
    Arg[2] = [c]
*/

请参阅

C# 编程指南

Command-line Building With csc.exe

Main() 和命令行参数(C# 编程指南)

如何:使用 foreach 访问命令行参数(C# 编程指南)

Main() 返回值(C# 编程指南)