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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ArthurA
  • 21
  • 1
  • 6
  • With command-line arguments https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments – Jasen Jul 18 '18 at 19:11

3 Answers3

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/

Thymine
  • 8,775
  • 2
  • 35
  • 47
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.

Neil N
  • 24,862
  • 16
  • 85
  • 145
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.

D. Kalb
  • 169
  • 1
  • 6
  • 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]? – ArthurA Jul 18 '18 at 19:27
  • 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. – D. Kalb Jul 18 '18 at 21:50