Console application trigger with parameter(s)

.NET CORE Console Application

LAI TOCA
2 min readMay 13, 2021
Photo from: https://dailydotnettips.com/how-to-pass-command-line-arguments-using-visual-studio/

Writing console application(s) for backend/background processing as routine task for most of software engineer(s). Sometime we would like to trigger our application according diverse environments or purposes.

For the .NET console application, we got input via the variable “args” under the Main method inside of Program.cs:

public static class Program
{
public static void Main(string[] args)
{
}
}

So we could passing some argument through command line:

{Path_Of_Your_App}\AppName arg1 arg2

Then under the application, we could retrieve argument(s) like this way :

public static class Program
{
public static void Main(string[] args)
{
Console.WriteLine($"arg1 = {args[0]}");
Console.WriteLine($"arg2 = {args[1]}")
}
}

Simply but not elegant, Why?

First, the input should be in sequence, if we passing: {Path_Of_Your_App}\AppName arg2 arg1. That’s mean value “arg2” now located on args[0] and value “arg1” located on args[1]. If someone missing the order you expected, something might went wrong.

Second, suppose that the “arg1” was optional, but “arg2” was mandatory. How could we skip passing the “arg1” but only “arg2”?

Third, passing only value “arg1” and “arg2” were mean less for understand the argument(s) and also for maintenance.

If we have key-value pair for self describe should be better and solve problems that we face:

# Order should not consider
{Path_Of_Your_App}\AppName --environment=arg2 --verbose=arg1
# Optional argument should be okay
{Path_Of_Your_App}\AppName --environment=arg2

For avoiding reinvent the wheels, we could adopt the library for parsing arguments via “FluentArgs”.

Install the library through Nuget.

Here was the simply example for using FluenArgs for handling above scenario.

public static class Program
{
public static void Main(string[] args)
{
FluentArgsBuilder.New()
.RegisterHelpFlag("-h", "--help")
.Parameter<int>("-v", "--Verbose")
.WithDescription("Verbose mode")
.WithExamples(1, 0)
.WithValidation(n => n == 0 || n == 1)
.IsOptionalWithDefault(0)
.Parameter("-env", "--environment")
.WithDescription("Run time environment.")
.WithExamples("Release", "QAS", "Debug")
.IsRequired()
// the sequence should be reverse as declared order
.Call(env => verbose =>
{
Console.WriteLine($"environment: {env}, Is verbose: {verbose}"); // run task....
})
.Parse(args);
}
}

The main benefit for using the “FluentArgs”:

⁂ With help document for description and example demonstration.

⁂ With default assign for optional argument(s).

⁂ With validation function(s) for applying rule implementation.

Reference

--

--

LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)