How to get command line parameters / file path

Asked

Viewed 557 times

5

I am developing an application, and accurate 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 there would be regions that would identify this command, for example.

switch url;
case r:

case v:

But I don’t know any function that identifies such parameters. How do I get them?

1 answer

3


It has two forms. One with parameter no 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’t do Main() nor pass on what you receive from him 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
        }
    }
}

I put in the Github for future reference.

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

There are some more powerful ready alternatives:

  • Ndesk.Options - Very powerful and flexible
  • Mono.Options - You can use in . NET, just include in your project.
  • Command Line Parser Library - Another complete well
  • You could list an immeasurable amount of options available from various libraries and public software. Here’s a tip to look for a ready one if you have a specific need. There’s a good chance someone has already done it.
  • Well, it’s just a flag, so thank you. As for user entries, no problems, after all this application is only for version control, and will not go on the deploy of the same.

  • Only one question. In the "Pre-build" compilation event how do I put this flag in the file path?

  • 1

    @Joãopaulopulga here shows where it is, on the debug screen http://csharp.2000things.com/2010/06/30/specify-command-line-arguments-in-visual-studio-2010/ (Command line Arguments)

  • 1

    Give a new question :)

  • 1

    @Bacco would also like to add in the compilation event, because this flag should also be beautiful when giving a Build to the project. (It would work the same way, but the solution has almost 300 projects. And thanks for editing the question. It looks much better :p)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.