Alon M
Alon M

Reputation: 1683

How to add run parameters to a C#

Its really really hard to explain what i am trying to do, so i will just explain what is the program i am trying to build.

I am building a Console App in C#.

I need to run it every day at 6:00. I have already built the timer for it, but i need it to get parameter with a "Name" like when you run it into PowerShell. I need to do something like that:

.\run.exe Name

which in my program I need the name in a string, and write with it.. and use it ofc. i will like to know how to add it, so i can do even:

.\run.exe Name Name2 Name3

Thanks again everyone, you are helping me here alot!

Upvotes: 3

Views: 8356

Answers (4)

flq
flq

Reputation: 22859

Your Console App entry point may look like

public static void Main(string[] args) { }

the args array contains all parameters you have passed via command line. The different elements are those that were separated by space.

So if you call your prog like prog.exe Name, args[0] will contain the value "Name". args.Length will have the value 1 . If you call prog.exe Name X, args.Length will be 2 and args[1] will be "X".

Upvotes: 3

Pleun
Pleun

Reputation: 8920

That is not a problem. The arguments you supply are available. Try this:

 static void Main(string[] args)
    {

        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine(args[i]);
        }
     }

if you want name, you might want to do something like

program.exe  /name=name /brand=brand /three=somethingelse

and parse the args for the /name=

This way you have more control over the arguments and the user can provide them in random order.

Upvotes: 0

AlG
AlG

Reputation: 15157

Pretty simple:

static void Main(string[] args)
{
  // ... use args[] to get at your arguments...
}

Upvotes: 0

N_A
N_A

Reputation: 19897

What you want is here: http://msdn.microsoft.com/en-us/library/acy3edy3.aspx

if (args.Length == 0)
{
    System.Console.WriteLine("Please enter a numeric argument.");
    return 1;
}
else if(args.Length == 1)
{
//do stuff here
}

etc

Upvotes: 0

Related Questions