C# Environment GetCommandLineArgs

Program icon (copyright Microsoft)

How does the Environment GetCommandLineArgs method work? Although you can receive command line arguments in the Main entry point in the C# language, the GetCommandLineArgs method can be used anywhere.

Example

This program shows how the args parameter is received in the Main entry point; it also shows how you can use Environment.GetCommandLineArgs. The main difference between these two approaches is that the first element in the string array returned by GetCommandLineArgs is the program executable path.

String Array Main Args Examples

This short C# example program demonstrates the Environment.GetCommandLineArgs method.

Program that uses Environment.GetCommandLineArgs [C#]

using System;

class Program
{
    static void Main(string[] args)
    {
	// Args does not contain the program path.
	Console.WriteLine(string.Join(",", args));

	// GetCommandLineArgs contains the program path as the first element.
	string[] array = Environment.GetCommandLineArgs();
	Console.WriteLine(string.Join(",", array));
    }
}

Output of the program [Arguments: dot net perls]
    (Second output line truncated.)

dot,net,perls
C:\Users\...\bin\Release\test.exe,dot,net,perls
Question and answer

Which should I use? It depends on your program. If you use the arguments immediately when the program begins, just use the args parameter. If your program uses the arguments later, you can use Environment.GetCommandLineArgs instead of passing the args parameter around a lot or storing it.

Summary

The Environment type reveals many useful methods in the .NET Framework for your C# programs. With the GetCommandLineArgs method, you can retrieve an array containing the program path and any command line arguments after that. This makes it simple to create customizable command line programs without an extra settings file.

.NET Framework Info
.NET