Skip to content

Instantly share code, notes, and snippets.

@analogrelay
Last active March 22, 2024 11:50
Show Gist options
  • Save analogrelay/f81dc1513c6c74f3b1841816bb3aba78 to your computer and use it in GitHub Desktop.
Save analogrelay/f81dc1513c6c74f3b1841816bb3aba78 to your computer and use it in GitHub Desktop.
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();
//}
}
}
@DanWahlin
Copy link

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

@frandi
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