作法:顯示命令列引數 (C# 程式設計指南)How to: Display Command Line Arguments (C# Programming Guide)

提供給命令列上可執行檔的引數,可以透過 Main 的選擇性參數來存取。Arguments provided to an executable on the command-line are accessible through an optional parameter to Main. 引數是以字串陣列的形式提供。The arguments are provided in the form of an array of strings. 陣列的每個項目都包含一個引數。Each element of the array contains one argument. 引數之間的空白字元會被移除。White-space between arguments is removed. 例如,請考慮這些虛擬可執行檔的命令列引動過程:For example, consider these command-line invocations of a fictitious executable:

命令列上的輸入Input on Command-line 傳遞至 Main 的字串陣列Array of strings passed to Main
executable.exe a b cexecutable.exe a b c "a""a"

"b""b"

"c""c"
executable.exe one twoexecutable.exe one two "one""one"

"two""two"
executable.exe "one two" threeexecutable.exe "one two" three "one two""one two"

"three""three"

注意

在 Visual Studio 中執行應用程式時,您可以在專案設計工具、偵錯頁中指定命令列引數。When you are running an application in Visual Studio, you can specify command-line arguments in the Debug Page, Project Designer.

範例Example

此範例顯示傳遞至命令列應用程式的命令列引數。This example displays the command line arguments passed to a command-line application. 所顯示的輸出是上表中的第一個項目。The output shown is for the first entry in the table above.

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

另請參閱See also