How to get an argument in a console program?

Therefore, I want other users to be able to run my argument sending options. how to do it?

+4
source share
7 answers

If you have the Main method (which you will have with the command line application), you can access them directly as an args string array parameter.

public static void Main(string[] args) { var arg1 = args[0]; var arg2 = args[1]; } 

If you use another place in your code, you can access the static method Environment.GetCommandLineArgs

 //somewhere in your code var args = Environment.GetCommandLineArgs(); var arg1 = args[0]; var arg2 = args[1]; 
+8
source

Do you mean args at startup? such as myapp.exe blah blah2 blah3

Make your main method as follows:

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

now args is an array of arguments passed to the program. So, in the example example, args[0] == "blah" , args[1] == "blah2" , etc.

+8
source

The program starts from a method with this signature

 public static void Main(string[] args) 

The args parameter will contain command line arguments, separated by spaces.

+4
source

While string [] args works just fine, Environment.GetCommandLineArgs is worth mentioning.

+3
source

You can read command line arguments from Main optional string[] parameter:

 static void Main(string[] args) { if (args.Length >= 1) { string x = args[0]; // etc... } } 

Note that the following declaration is also indicated for the Main method, but then you do not have access to the command line arguments:

 static void Main() { // ... } 

See more details.

+2
source

This is supported by default, and the arguments will appear in the args array passed to your program.

 public static void Main(string[] args) 

If you say

 App.exe Hello World What Up 

At the command line, you will get an args array as follows:

 [0] = "Hello" [1] = "World" [2] = "What's" [3] = "Up" 

It is up to you to determine which arguments you want, how they will be formatted, etc.

+2
source

try the following:

http://sourceforge.net/projects/csharpoptparse/

http://www.codeproject.com/KB/recipes/command_line.aspx

they basically allow you to define arguments and parse them in an OO way, rather than having many string comparisons and the like. I used the same for Java and it was great

+2
source

Source: https://habr.com/ru/post/1310544/


All Articles