Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read command line switch

Tags:

I'm trying to read user arguments in a C# application. I know how to read them based on position with

string[] args = Environment.GetCommandLineArgs();

but I'd like to read them from switches such as

app.exe /f /d:foo

I'm really struggling to find any information on doing this...

like image 227
MTeck Avatar asked Mar 16 '12 18:03

MTeck


People also ask

How do I use command line switches?

Use a switch once by adding it to the Run commandIn the Run dialog box, type a quotation mark, enter the full path for the app's .exe file, and then type another quotation mark. Alternatively, click Browse to locate and select the file. In this case, the quotation marks are supplied automatically.

What is a switch or option in command line?

A command line switch (also known as an option, a parameter, or a flag) acts as a modifier to the command you are issuing in the Command Prompt window, in a batch file, or in other scripts. Usually, a switch is a single letter preceded by a forward slash.

How do you access command line arguments from within a shell script?

The special character $# stores the total number of arguments. We also have $@ and $* as wildcard characters which are used to denote all the arguments. We use $$ to find the process ID of the current shell script, while $? can be used to print the exit code for our script.

How do you pass a command line argument?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.


1 Answers

Why don't you just parse the array of arguments passed and act based on them, like this

foreach (string arg in args)
{
    switch (arg.Substring(0, 2).ToUpper())
    {
        case "/F":
            // process argument...
            break;
        case "/Z":
            // process arg...
            break;
        case "/D":
            paramD = arg.Substring(3);
            break;
        default:
            // do other stuff...
            break;
    }
}
like image 89
Jason Avatar answered Nov 05 '22 21:11

Jason