Search code examples
c#.netcommand-linecommandcommand-line-arguments

Create custom command line parameters for C# console application


I have a C# console application that I'm gonna run from the command line, and it should take some information as input and serialize the given values into a json file, but the classic args[] is not what I want.

Let's say I have 10 particular data that I may want to pass, like name, model, state, version, number etc, but not necessarily all of them, only name would be mandatory. So, for example, I would like to be able to run the following command successfully or other random combination of the 10 parameters Example:

myApp.exe --name paramName

myApp.exe --name paramName --version 5

myApp.exe --name paramName --model R7 --state on

How can I achieve this?

Thank you!


Solution

  • I'd rather suggest you to use some tool to do this.

    For example, I usually use: https://github.com/commandlineparser/commandline

    That tool allows you to write your options in a class which is automatically filled when the program loads.

    Here the sample for their git:

    class Program
    {
        public class Options
        {
            [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
            public bool Verbose { get; set; }
        }
    
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments<Options>(args)
                   .WithParsed<Options>(o =>
                   {
                       if (o.Verbose)
                       {
                           Console.WriteLine($"Verbose output enabled. Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example! App is in Verbose mode!");
                       }
                       else
                       {
                           Console.WriteLine($"Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example!");
                       }
                   });
        }
    }