Environment.GetCommandLineArgs Método

Definição

Retorna uma matriz de cadeia de caracteres que contém os argumentos de linha de comando para o processo atual.Returns a string array containing the command-line arguments for the current process.

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

Retornos

String[]

Uma matriz de cadeias de caracteres em que cada elemento contém um argumento da linha de comando.An array of strings where each element contains a command-line argument. O primeiro elemento é o nome do arquivo executável e os seguintes zero ou mais elementos contêm os argumentos de linha de comando restantes.The first element is the executable file name, and the following zero or more elements contain the remaining command-line arguments.

Exceções

O sistema não dá suporte a argumentos de linha de comando.The system does not support command-line arguments.

Exemplos

O exemplo a seguir exibe os argumentos de linha de comando do aplicativo.The following example displays the application's command line arguments.

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

Comentários

O primeiro elemento na matriz contém o nome do arquivo do programa em execução.The first element in the array contains the file name of the executing program. Se o nome do arquivo não estiver disponível, o primeiro elemento será igual a String.Empty .If the file name is not available, the first element is equal to String.Empty. Os elementos restantes contêm quaisquer tokens adicionais inseridos na linha de comando.The remaining elements contain any additional tokens entered on the command line.

No .NET 5,0 e versões posteriores, para publicação de arquivo único, o primeiro elemento é o nome do executável do host.In .NET 5.0 and later versions, for single-file publishing, the first element is the name of the host executable.

O nome do arquivo de programa pode, mas não é necessário, incluir informações de caminho.The program file name can, but is not required to, include path information.

Os argumentos de linha de comando são delimitados por espaços.Command line arguments are delimited by spaces. Você pode usar aspas duplas (") para incluir espaços em um argumento.You can use double quotation marks (") to include spaces within an argument. No entanto, a aspa simples ('), no entanto, não fornece essa funcionalidade.The single quotation mark ('), however, does not provide this functionality.

Se uma aspa dupla segue duas ou um número par de barras invertidas, cada um deles continuando o par de barras invertidas é substituído por uma barra invertida e as aspas duplas são removidas.If a double quotation mark follows two or an even number of backslashes, each proceeding backslash pair is replaced with one backslash and the double quotation mark is removed. Se uma aspa dupla seguir um número ímpar de barras invertidas, incluindo apenas uma, cada par anterior será substituído por uma barra invertida e a barra invertida restante será removida; no entanto, nesse caso, a aspa dupla não é removida.If a double quotation mark follows an odd number of backslashes, including just one, each preceding pair is replaced with one backslash and the remaining backslash is removed; however, in this case the double quotation mark is not removed.

A tabela a seguir mostra como argumentos de linha de comando podem ser delimitados e pressupõe-se MyApp que o aplicativo de execução atual.The following table shows how command line arguments can be delimited, and assumes MyApp as the current executing application.

Entrada na linha de comandoInput at the command line Argumentos de linha de comando resultantesResulting command line arguments
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

Para obter a linha de comando como uma única cadeia de caracteres, use a CommandLine propriedade.To obtain the command line as a single string, use the CommandLine property.

Aplica-se a

Confira também