Antoine Aubry
Antoine Aubry

Reputation: 12469

How to access command line parameters outside of Main in C#

I am writing a .NET class that needs to parse the command line of the process. I don't want to have a dependency between the Main() method and that class. How can the class access the command line?

Upvotes: 23

Views: 12690

Answers (5)

Stéphane B.
Stéphane B.

Reputation: 3280

If you use .NET Compact Framework, Environment.GetCommandLineArgs() method isn't implemented and System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments returns always empty string, so you must use main function and pass arguments to your others classes.

An example :

[MTAThread]
static void Main(String[] commandLineArguments)
{
  CommandLineHelper.parse(commandLineArguments);
}

public static class CommandLineHelper
{
  public static void parse(String[] commandLineArguments) {
    // add your code here
  }
}

Upvotes: 5

Myname
Myname

Reputation: 41

String[] myStr = Environment.GetCommandLineArgs();

its always good to complete the example.

Upvotes: 2

Neil Barnwell
Neil Barnwell

Reputation: 42125

Create a class that holds your application's options. In the main method create an instance of that class, initialise it with the command line arguments, and pass it in to the classes that need it.

Alternatively, you could have the class initialised at any time thereafter by having it created via a CustomConfigClass.Create() method that uses Environment.GetCommandLineArgs().

The first option would be my recommendation, because it makes the class easier to prepare for unit testing and switching to an alternative method of configuration at a later date without breaking the application due to a dependency on the command line.

Upvotes: 1

Scott Langham
Scott Langham

Reputation: 60331

System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments

Upvotes: 1

itowlson
itowlson

Reputation: 74802

Call Environment.GetCommandLineArgs().

Upvotes: 46

Related Questions