views:

458

answers:

3

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?

+7  A: 

Call Environment.GetCommandLineArgs().

itowlson
A: 

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

Scott Langham
+1  A: 

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.

Neil Barnwell
The first option still requires the main method to know about the other class, so it does not solve my problem. I'm using an IOC container, therefore I will create a service that exposes the GetCommandLineArgs functionality, and make my other service depend from it. Thanks.
Antoine Aubry
That misses my point slightly, though. If you're using IoC, then don't have a service to return the command line args, have a service interface that returns the config, and implement that with a class that gets it from the command line. That way you can replace with another class for unit testing.
Neil Barnwell