Last active
March 22, 2024 11:50
-
-
Save analogrelay/f81dc1513c6c74f3b1841816bb3aba78 to your computer and use it in GitHub Desktop.
My Command Line Template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
{ | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
//} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice 👍