简体   繁体   中英

Passing arguments to console app with specific format c#

I wanna pass arguments to c# console app with this specific format. Suppose my app's exe name is SmsSender, I wanna this format in my cmd: SmsSender -m message -p phonenumber

How can I do this?

You just write that command into a command prompt window, exactly as you have written in there

Inside your c# app you have a static void Main(string[] args) and the args array will have 4 elements:

args[0] = "-m";
args[1] = "message";
args[2] = "-p";
args[3] = "phonenumber";

But be aware that if you don't wrap your message in "quotes" (in the command prompt) then every word in the message will be a different entry in args

Refer to this Microsoft Docs How to Display arguments

So in your case in you console app in your Main method you will have something like this:

class CommandLine
{
     static void Main(string[] args)
    {
        // The Length property provides the number of array elements.
        Console.WriteLine($"parameter count = {args.Length}");
        // Get values using the `args` array in your case you will have:
        // args[0] = "-m";
        // args[1] = "message";
        // args[2] = "-p";
        // args[3] = "phonenumber";

        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine($"Arg[{i}] = [{args[i]}]");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM