1

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!

  • ArthurA
1

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

2 Comments

Oh I understand this now I was trying to figure how I can reference the parameters that I type in the console, so to clarify I can set a variable in the code to equal args[n]?
At the begin of your main you could determine your input values. That means you check the length of args and check if it corresponds to the your definitions for the arguments and then you can extract those values from the array and assign them to local variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.