muncherelli
muncherelli

Reputation: 2903

Command Line Parameters

I want to deploy a piece of software to pcs that will need to be able to tell the program a few pieces of information. I do not want to use a configuration file because the exe will be located on a shared drive and they will not have access to run their own config. Would a command line parameter be the best way to do this? If so, how would I pass this and pick it up inside of a c# program?

Upvotes: 4

Views: 486

Answers (3)

JaredPar
JaredPar

Reputation: 755457

Yes the command line is a good way of passing information to a program. It is accessible from the Main function of any .Net program

public static void Main(string[] args) {
   // Args is the command line 
}

From elsewhere in the program you can access it with the call Environment.GetCommandLineArgs. Be warned though that the command line information can be modified once the program starts. It's simply a block of native memory that can be written to by the program

Upvotes: 5

Sam Trost
Sam Trost

Reputation: 2173

If you dont want to override the main method, you can use the Environment class.

foreach (string arg in Environment.GetCommandLineArgs())
{
    Console.WriteLine(arg);
}

Upvotes: 8

Mark Rushakoff
Mark Rushakoff

Reputation: 258478

The simplest way to read a command line argument in C# is to make sure your Main method takes a string[] parameter -- that parameter is filled with the arguments passed from the command line.

$ cat a.cs
class Program
{
    static void Main(string[] args)
    {
        foreach (string arg in args)
        {
            System.Console.WriteLine(arg);
        }
    }
}
$ mcs a.cs
$ mono ./a.exe arg1 foo bar
arg1
foo
bar

Upvotes: 2

Related Questions