Parsing Command Line Arguments in .NET Core

Programming .NET Core C#

Microsoft once released the Microsoft.Extensions.CommandLineUtils library. However this project is no longer maintenanced.

However with natemcmaster/CommandLineUtils there is another NuGet library available that builds up on the library from Microsoft and the maintaner will continue to make improvements, release updates, and also accept contributions.

With this library the parsing of CommandLine Arguments and Options becomes quite easy:

public class Program
{
[Argument(0)]
[Required]
public string FirstName { get; }

[Argument(1)]
public string LastName { get; } // this one is optional because it doesn't have `[Required]`

private void OnExecute()
{
Console.WriteLine($"Hello {FirstName} {LastName}");
}

public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);
}
public class Program
{
[Option("-b")]
public int BlankLines { get; }

[Argument(0)]
public string[] Files { get; } // = { "file1.txt", "file2.txt", "file3.txt" }

private void OnExecute()
{
if (Files != null)
{
foreach (var file in Files)
{
// do something
}
}
}

public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);
}

The library also provides basic input helpers like f.e:

    class Program
{
private void OnExecute()
{
bool reallyDoIt = Prompt.GetYesNo("Are your shure about this?", false, ConsoleColor.Yellow);
string yourName = Prompt.GetString("What's your name: ", "John Doe");
string secrPWDP = Prompt.GetPassword("Enter your password: ");
}

public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);
}