ArthurA
ArthurA

Reputation: 21

Execute a C# console application with parameters in command prompt

I am currently writing a console application that deletes old log files, now I got that functionality working, I was trying to figure out how to execute a program with parameters from Command Prompt.

Example:

FileDeleter.exe days 3

where I'm running the program and telling it to delete 3 days worth of log files. Can these arguments be passed as variables into the code? I am not sure how this is accomplished.

Thanks for the help!

Upvotes: 1

Views: 6676

Answers (3)

Thymine
Thymine

Reputation: 9195

If you need more advanced parsing, there are of course libraries available Best way to parse command line arguments in C#?

https://github.com/BizArk/BizArk3

http://fclp.github.io/fluent-command-line-parser/

Upvotes: 1

D. Kalb
D. Kalb

Reputation: 179

As @Neil N already mentionend, you have to define a your main method like this:

static void Main(string[] args)

args will then contain the arguments you passed.

If you run your program like this: FileDeleter.exe days 3, args[0] would contain the string "days" and args[1] would contain the string "3". Pay attention here that the latter one will be a string despite the fact that you passed a number. Therefor you might have to parse it to a number before using it.

Upvotes: 0

Neil N
Neil N

Reputation: 25258

your void main should take an array of strings as an arg:

static void Main(string[] args)

You can then parse the args as you see fit.

Upvotes: 0

Related Questions