Daily Archives: July 7, 2007

Getting the command line on .net

There appear to be 3 ways to get the command line in .net. The first and simplest is to just declare a string array in the arguments for your main method. This gives you the parameters as a list. All the quotes and breaks between the words have been interpreted for you and you just have to use the list. The one thing missing from this is the program file that was traditionally the first element in languages like C.

static void Main(string[] args)
{

The second is to call System.Environment.GetCommandLineArgs(). This again gives you an array. The main reason you might want this is that it has the program name as the first element. Useful if you want to find the path* the program was executed from or want to put the actual program name in a usage message for example.

The third is to get the System.Environment.CommandLine. This is a string of the complete command line. If you are converting over an old command line parser to .net from a language that received the command line in that format (VO springs to mind) you might want to use it. Alternatively commands like echo that need the exact command line with spacing intact would want to get it this way.

* don’t trust the first parameter completely, it can be faked.

Follow

Get every new post delivered to your Inbox.

Join 64 other followers