Parsing Command Line Arguments with Command Line Parser Library

When writing .Net console applications we often need to parse command line arguments that the user specified when launching the application.

We get these arguments passed into the program in the args parameter of Main()

static void Main(string[] args)

If our application only has a single simple parameter then it’s probably ok to just parse it ourselves.

Once the number and type of parameters increase then there’s a whole host of complexity that can creep in:

  • What if values need converting to enum values?
  • How to handle arguments that takes a list of values?
  • How to implement verb style arguments like “git push”?
  • What if parameters are in different order?
  • What about optional parameters and should we use default values if they’re not supplied?
  • What about arguments that are mutually exclusive?

While we can program our console applications to account for these things it could be quite a lot of work and testing to implement effectively.

It makes sense in these cases to use a ready-built library such as Command Line Parser Library.

Command Line Parser Library Basics

This library represents arguments by creating a class and decorating its properties that represent args with the [Option] attribute.

class SomeOptions
{
    [Option('n', "name", Required=true)]
    public string Name { get; set; }

    [Option('a', "age")]
    public int Age { get; set; }
}

Here this class is stating that we should always have a name argument (Required=true) and we can specify it at the command line with the shorthand “-n” or longer --name”.

The age argument is optional and can be specified with “-a” or --age”.

So from the command line we could type:

myconsoleapplication.exe -n Jason --age 99

In our Main method we can now parse these arguments into  an instance of our SomeOptions class.

static void Main(string[] args)
{
    var options = new SomeOptions();

    CommandLine.Parser.Default.ParseArguments(args, options);

    // options.Name will = Jason
    // options.Age will = 99
}

The ParseArguments method takes the array of string args from the command line and populates our SomeOptions instance which we can then use in a strongly typed way.

There’s a lot more to this library such as implementing verb style arguments, strict parsing, and creating help text, all of which I cover in my Pluralsight Building .NET Console Applications in C# course.

SHARE:

Handling CTRL-C in .NET Console Applications

By default, pressing CTRL-C while a console application is running will cause it to terminate.

If we want to prevent this we can set Console.TreatControlCAsInput Property to true. This will prevent CTRL-C from terminating the application. To terminate now, the user needs to close the console window or hit CTRL-BREAK instead of the more usual and well-known CTRL-C.

class Program
{
    private static void Main(string[] args)
    {
        Console.TreatControlCAsInput = true;
        while (true)
        {
        }
    }
}

There is also the Console.CancelKeyPress event. This event is fired whenever CTRL-C or CTRL-BREAK is pressed. It allows us to decide whether or not to terminate the application.

More...

SHARE:

Getting Input From Alternative Sources in .NET Console Applications

Using the Console.SetIn Method allows us to specify an alternative source (TextReader stream).

For example suppose we have the following “names.txt” text file:

Sarah
Amrit
Gentry
Jack

We can create a new stream that reads from this file whenever we perform a Console.ReadLine(). Now when we call ReadLine, a line is read from the text file rather than the keyboard.

We can use the Console.OpenStandardInput() method to reset input back to the keyboard.

The code below creates the following output:

More...

SHARE:

Creating a Spinner Animation in a Console Application in C#

If we have a longer running process taking place in a console application, it’s useful to be able to provide some feedback to the user so they know that the application hasn’t crashed. In a GUI application we’d use something like an animated progress bar or spinner. In a console application we can make use of the SetCursorPosition() method to keep the cursor in the same place while we output characters, to create a spinning animation.

consolespinner1

While the code below could certainly be improved, it illustrates the point:

More...

SHARE:

Setting Foreground and Background Colours in .NET Console Applications

In addition to doing some fun/weird/useful/annoying things in Console applications, we can also set foreground and background colours.

To set colours we use the Console.BackgroundColor and Console.ForegroundColor properties.

When we set these properties we supply a ConsoleColor. To reset the colours back to the defaults we can call the ResetColor() method.

using System;

namespace ConsoleColorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Default initial color");

            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Black on white");
            Console.WriteLine("Still black on white");

            Console.ResetColor();

            Console.WriteLine("Now back to defaults");

            Console.ReadLine();

        }
    }
}

The above code produces the following output:

More...

SHARE:

3 Surprising Things to Do with the Console in C#

The Console class can do more than just WriteLine().

Here’s 3 fun/weird/useful/annoying things.

1. Setting The Console Window Size

The Console.SetWindowSize(numberColumns, numberRows) method sets the console window size.

Console.SetWindowSize

 

To annoy your users (or create a “nice” console opening animation) as this animated GIF shows you could write something like:

for (int i = 1; i < 40; i++)
{
    Console.SetWindowSize(i,i);
    System.Threading.Thread.Sleep(50);
}

2. Beeping Consoles

The Console.Beep() method emits a beep from the speaker(s).

We can also specify a frequency and duration.

More...

SHARE: