This demo illustrates how to extend CLArgs functionality to meet your custom needs.
Custom Context property type
Imagin you want a Context with a property having custom type that is not supported out of the box. There is no built-in converter to convert command-line arguments into a property of type DirectoryInfo, and we need to create and register a custom converter.
publicclassDemo4Context{ [OptionDescriptor("Directory",new []{"Dir","d"}, helpText :"Specify an existing directory." )]publicDirectoryInfo? Dir { get; set; }}
Define the custom DirectoryInfo converter
/// <summary>/// Custom argument to DirectoryInfo converter./// </summary>publicclassDirectoryInfoConverter:IArgumentConverter{publicobjectConvert(string optionValue,string optionName,ErrorDetailList errors,Type targetType) {if( !Directory.Exists(optionValue))errors.AddError(optionName,$"The specified directory does not exist: '{optionValue}'.");returnnewDirectoryInfo(optionValue); }}
Register the custom during start-up using ContextBuilderConfigureConverters.
//...var host =CommandHostBuilder.Create(args).Build();ContextBuilder cb =host.Services.GetRequiredService<ContextBuilder>();cb.ConfigureConverters( converters =>converters.AddCustomConverter(typeof(DirectoryInfo),newDirectoryInfoConverter()));// The ContextBuilder.Build() is called implicitly right before the Command executes.host.Run();
Use the erroscollection instead of throwing exception if you want to collect and return multiple error results.
if( optionValue.Length<3) errors.AddError(optionName,"Option value is too short!");if( !Directory.Exists(optionValue))errors.AddError(optionName,$"The specified directory does not exist: '{optionValue}'.");