[英]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. 我在哪里运行程序,并告诉它删除3天的日志文件。 Can these arguments be passed as variables into the code? 这些参数可以作为变量传递到代码中吗? I am not sure how this is accomplished. 我不确定如何实现。
Thanks for the help! 谢谢您的帮助!
If you need more advanced parsing, there are of course libraries available Best way to parse command line arguments in C#? 如果需要更高级的解析,则当然有可用的库在C#中解析命令行参数的最佳方法?
https://github.com/BizArk/BizArk3 https://github.com/BizArk/BizArk3
http://fclp.github.io/fluent-command-line-parser/ http://fclp.github.io/fluent-command-line-parser/
your void main should take an array of strings as an arg: 您的void main应该将字符串数组作为arg:
static void Main(string[] args)
You can then parse the args as you see fit. 然后,您可以根据需要解析args。
As @Neil N already mentionend, you have to define a your main method like this: 正如@Neil N已经提到的那样,您必须定义一个主要方法,如下所示:
static void Main(string[] args)
args will then contain the arguments you passed. 然后args将包含您传递的参数。
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". 如果您这样运行程序: FileDeleter.exe days 3 ,则args [0]将包含字符串“ days”,而args [1]将包含字符串“ 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. 因此,您可能必须在使用它之前将其解析为一个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.