Environment.GetCommandLineArgs 方法

定義

傳回字串陣列,包含目前處理序的命令列引數。

public:
 static cli::array <System::String ^> ^ GetCommandLineArgs();
public static string[] GetCommandLineArgs ();
static member GetCommandLineArgs : unit -> string[]
Public Shared Function GetCommandLineArgs () As String()

傳回

String[]

字串陣列,其每個元素都包含一個命令列引數。 第一個元素是可執行檔名稱,後面的零或多個元素包含其餘的命令列引數。

例外狀況

系統不支援命令列引數。

範例

下列範例會顯示應用程式的命令列引數。

using namespace System;

int main()
{
   Console::WriteLine();
   
   //  Invoke this sample with an arbitrary set of command line arguments.
   array<String^>^ arguments = Environment::GetCommandLineArgs();
   Console::WriteLine( "GetCommandLineArgs: {0}", String::Join( ", ", arguments ) );
}
/*
This example produces output like the following:
    
    C:\>GetCommandLineArgs ARBITRARY TEXT
    
      GetCommandLineArgs: GetCommandLineArgs, ARBITRARY, TEXT
*/
using System;

class Sample
{
    public static void Main()
    {
        Console.WriteLine();
        //  Invoke this sample with an arbitrary set of command line arguments.
        string[] arguments = Environment.GetCommandLineArgs();
        Console.WriteLine("GetCommandLineArgs: {0}", string.Join(", ", arguments));
    }
}
/*
This example produces output like the following:

    C:\>GetCommandLineArgs ARBITRARY TEXT

      GetCommandLineArgs: GetCommandLineArgs, ARBITRARY, TEXT
*/
open System

//  Invoke this sample with an arbitrary set of command line arguments.
let arguments = Environment.GetCommandLineArgs()

String.concat ", " arguments
|> printfn "\nGetCommandLineArgs: %s"

// This example produces output like the following:
//     C:\>GetCommandLineArgs ARBITRARY TEXT
//
//       GetCommandLineArgs: GetCommandLineArgs, ARBITRARY, TEXT
Class Sample
   Public Shared Sub Main()
      Console.WriteLine()
      '  Invoke this sample with an arbitrary set of command line arguments.
      Dim arguments As String() = Environment.GetCommandLineArgs()
      Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments))
   End Sub
End Class
'This example produces output like the following:
'    
'    C:\>GetCommandLineArgs ARBITRARY TEXT
'    
'      GetCommandLineArgs: GetCommandLineArgs, ARBITRARY, TEXT
'

備註

陣列中的第一個專案包含執行中程式的檔案名。 如果檔案名無法使用,則第一個專案等於 String.Empty 。 其餘元素包含命令列上輸入的任何其他權杖。

在 .NET 5 和更新版本中,針對單一檔案發行,第一個專案是主機可執行檔的名稱。

程式檔名可以包含路徑資訊,但不需要包含路徑資訊。

命令列引數是以空格分隔。 您可以使用雙引號 (「) 在引數中包含空格。 不過,單引號 () 不提供這項功能。

如果雙引號後面接著兩個或偶數個反斜線,則會以一個反斜線取代每個繼續反斜線配對,並移除雙引號。 如果雙引號遵循奇數反斜線,包括一個反斜線,則會以一個反斜線取代每個前面的配對,並移除其餘反斜線;不過,在此情況下,不會移除雙引號。

下表顯示如何分隔命令列引數,並假設 MyApp 為目前執行中的應用程式。

命令列上的輸入 產生的命令列引數
MyApp alpha beta MyApp, alpha, beta
MyApp "alpha with spaces" "beta with spaces" MyApp, alpha with spaces, beta with spaces
MyApp 'alpha with spaces' beta MyApp, 'alpha, with, spaces', beta
MyApp \\\alpha \\\\"beta MyApp, \\\alpha, \\beta
MyApp \\\\\"alpha \"beta MyApp, \\"alpha, "beta

若要取得命令列做為單一字串,請使用 CommandLine 屬性。

適用於

另請參閱