2

I'm sorry, I can't really google this because I'm not sure how to properly say this in a few words.

But basically I'd like to have something like, when you open your program via dos or via a shortcut looking like this:

"c:\program.exe" value1 value2

that my application would be able to use these values. But also when I don't enter the values, that my application still starts fine.

I hope that made any sense what I'm trying to say here

Any help is appereciated

4 Answers4

6

Those are the args that get passed to your main function:

public static void main (string[] args)
{
    // Check to see if at least two args were passed in.
    if(args.Length >= 2)
    {
        Console.WriteLine(args[0]); // value1
        Console.WriteLine(args[1]); // value2
    }
}

Keep in mind, though, that there's no way to guarantee the order of the args passed in or that they are the values you expect. You should use named arguments and then parse and validate them at the beginning of your application. Your command might look something like:

C:\program.exe /V1 value1 /V2 value2

As for a good list of parsers, I would check out:

.net - Best way to parse command line arguments in C#

Community
  • 1
  • 1
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • Lol... I knew it'd be insanely simple, I just didn't know how to say what I want exactly. Thanks ^^ –  Jul 04 '12 at 15:06
1

Have a peek at the Microsoft tutorial for command line parameters

If a parameter isn't provided then just use some defauls.

public static void Main(string[] args)
{
   // The Length property is used to obtain the length of the array. 
   // Notice that Length is a read-only property:
   Console.WriteLine("Number of command line parameters = {0}",
      args.Length);
   for(int i = 0; i < args.Length; i++)
   {
       Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
   }

   if(args.length < 2) 
   { 
       x = 1;
   }  else {
   {
       x = Arg[2]; 
   }

}

John Mitchell
  • 9,653
  • 9
  • 57
  • 91
1

When you create a executable you have a Main function that has Main(string[] args), here you can read the params which you used to call the program.

If you want default values, you can make a class variable with a defined value (or use the application properties) and if the program program is called with parameters overwrite them.

Hope it helps you :)

msancho
  • 181
  • 1
  • 6
0

Execute your Program.exe from commandline this way

C:\Program Test1 Test2

To get knowledge on how to this in C# please use the link MSDN

HatSoft
  • 11,077
  • 3
  • 28
  • 43