How to get command line parameters / file path

4

I'm developing an application, and I need it by parameters / commands next to the file path.

For example, these flags :

C:/caminho_do_arquivo -r 

C:/caminho_do_arquivo -v

And in the code would have regions that would identify this command, for example.

switch url;
case r:

case v:

But I do not know of any function that identifies such parameters. How do I get them?

    
asked by anonymous 02.04.2015 / 20:03

1 answer

3

There are two ways. One with parameter in Main() :

void Main(string[] args) {
    foreach(var arg in args) {
        switch(arg) {
            case "-r":
            //faz algo aqui
            case "-v":
            //faz algo aqui
        }
    }
}

And if you can not do it in Main() and do not pass what you get from it to another method, you can use Environment.GetCommandLineArgs :

void Main() {
    var args = Environment.GetCommandLineArgs();
    foreach(var arg in args) {
        switch(arg) {
            case "-r":
            //faz algo aqui
            case "-v":
            //faz algo aqui
        }
    }
}

At least this is simplified. Of course, the data received must be better validated. Depending on what you are going to get, if it is something other than flags you may need a more complex logic. If you are sure you will only have one flag , you can simplify by removing the loop from foreach . But remember this is a user input, something crazy might come in.

There are some more powerful ready-made alternatives:

  • NDesk.Options - Powerful and flexible
  • Mono.Options insert the link description here - You can use it in .Net, just include it in your project.
  • Command Line Parser Library - Another very complete
  • You could list an immeasurable number of options available from various public libraries and software. The tip is to look for a prompt if you have any specific needs. It's great that somebody has already done it.
02.04.2015 / 20:14