C#: NConsoler – Cool code to handle Console Application arguments

I’ve been writing a few console applications lately, and one thing I’ve always found not so easy to implement, was handling required/optional arguments that the user passes to my application.

Now, firstly, I’m not a software developer, I’m a server/network administrator. Writing C# code is just something I enjoy and find helps when managing my various servers.

Having just finished writing an application, I was talking with a colleague about this very subject, and he suggested I take a look at the NConsoler project. What NConsoler does is make a very structured way of defining which arguments are required, which are optional.

Not only that, but it also produces its own output when arguments are missing or not recognised. Get this. It even implements a usage output!

For example:


using System;
using NConsoler;

class Program
{
static void Main(string[] args)
{
Consolery.Run();
}

[Action("Deletes some objects")]
public static void Add(
[Required(Description = "Object count")]
int count,

[Required(Description = "Object description")]
string description,

[Optional(false, "b", "bk", Description = "Boolean value")]
bool book,

[Optional("", "c")]
string comment,

[Optional(1)]
int length)
{
Console.WriteLine("Add {0} {1} {2} {3}", count, description, book, comment);
}

[Action("Deletes some objects")]
public static void Remove(
[Required(Description = "Object description")]
string description)
{
Console.WriteLine("Remove {0} {1} {2} {3}", count, description, book, comment);
}
}


If you were to run the built executable you'd use the following syntax (for example):

 Program.exe Add 5 description /book 


Arguments starting with a '/' are the optional ones and the 'Description = ' of the [Required] and [Optional] sections is used for the automatically produced help.

For the [Optional] section we also have a default value for when its not specified and aliases. In my example above you could use /b or /bk instead of /book.

When specifying an optional argument of a different type to Boolean you use the format: /book:true

Have a play, and I think you'll agree its quite useful!!

0 Comments