Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My Command Line Template
using System;
using System.Runtime.Serialization;
namespace MyTool
{
[Serializable]
internal class CommandLineException : Exception
{
public CommandLineException()
{
}
public CommandLineException(string message) : base(message)
{
}
public CommandLineException(string message, Exception innerException) : base(message, innerException)
{
}
protected CommandLineException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
using System;
using System.Diagnostics;
using System.Linq;
using McMaster.Extensions.CommandLineUtils;
namespace MyTool
{
[Command(Description = "... Description ...")]
internal class Program
{
private static int Main(string[] args)
{
#if DEBUG
if (args.Any(a => a == "--debug"))
{
args = args.Where(a => a != "--debug").ToArray();
Console.WriteLine($"Ready for debugger to attach. Process ID: {Process.GetCurrentProcess().Id}.");
Console.WriteLine("Press ENTER to continue.");
Console.ReadLine();
}
#endif
try
{
return CommandLineApplication.Execute<Program>(args);
}
catch(CommandLineException clex)
{
var oldFg = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(clex.Message);
Console.ForegroundColor = oldFg;
return 1;
}
catch(Exception ex)
{
var oldFg = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Unhandled exception:");
Console.Error.WriteLine(ex.ToString());
Console.ForegroundColor = oldFg;
return 1;
}
}
//// If a multi-command app...
//public void OnExecute(CommandLineApplication app)
//{
// app.ShowHelp();
//}
}
}
@evilpilaf

This comment has been minimized.

Copy link

evilpilaf commented Aug 11, 2018

This is genius!!!

@DanWahlin

This comment has been minimized.

Copy link

DanWahlin commented Aug 11, 2018

Love it - great idea to simplify things. Thanks for sharing.

@frandi

This comment has been minimized.

Copy link

frandi commented Aug 12, 2018

Nice 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.