如何使用命令行解析器库以防错误发生?

时间:2015-10-06 15:24:55

标签: c# command-line console-application command-line-arguments command-line-parsing

我使用Command Line Parser Library来解析命令行参数。

我已宣布课程Options

internal class Options
{
    [Option('r', "read", Required = true,
        HelpText = "Input file to be processed.")]
    public string InputFile { get; set; }

    [Option('f', "date from", Required = false,
        HelpText = "Date from which get statistic.")]
    public string DateFrom { get; set; }

    [Option('t', "date to", Required = false,
        HelpText = "Date to which get statistic.")]
    public string DateTo { get; set; }

    [Option('v', "verbose", DefaultValue = true,
        HelpText = "Prints all messages to standard output.")]
    public bool Verbose { get; set; }

    [ParserState]
    public IParserState LastParserState { get; set; }

    [HelpOption]
    public string GetUsage()
    {
        return HelpText.AutoBuild(this,
            (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
    }
}

这就是我尝试使用Parser的方式:

private static void Main(string[] args)
    {
        Console.WriteLine("Hello and welcome to a test application!");

        string filePath = string.Empty;
        string fromDate = string.Empty, toDate = string.Empty;
        DateTime dateTo, dateFrom;

        Console.ReadLine();

        var options = new Options();
        if (CommandLine.Parser.Default.ParseArguments(args, options))
        {
            // Values are available here
            if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);

            if (string.IsNullOrWhiteSpace(options.InputFile))
            {
                filePath = ConfigurationManager.AppSettings["FilePath"];
                if (string.IsNullOrWhiteSpace(filePath))
                {
                    filePath = Directory.GetCurrentDirectory() + @"\Report.xlsx";
                }
            }
            else
            {
                filePath = options.InputFile;
            }
            fromDate = string.IsNullOrWhiteSpace(options.DateFrom)
                ? ConfigurationManager.AppSettings["DateFrom"]
                : options.DateFrom;
            toDate = string.IsNullOrWhiteSpace(options.DateTo) ? ConfigurationManager.AppSettings["DateTo"] : options.DateTo;
        }
        else
        {
            return;
        }

//其他代码     }

但是如果出现一些错误,应用程序就会停止工作。

所以我想知道如何在错误的情况下重复输入值的第一步。

while (!CommandLine.Parser.Default.ParseArguments(args, options)){...} - makes loop

1 个答案:

答案 0 :(得分:1)

我使用Command Line Parser。

为多个项目声明一个通用的包装器

public class CommandLineOptions
{
    public const bool CASE_INSENSITIVE = false;
    public const bool CASE_SENSITIVE = true;
    public const bool MUTUALLY_EXCLUSIVE = true;
    public const bool MUTUALLY_NONEXCLUSIVE = false;
    public const bool UNKNOWN_OPTIONS_ERROR = false;
    public const bool UNKNOWN_OPTIONS_IGNORE = true;

    public CommandLineOptions();

    public string[] AboutText { get; set; }
    [ParserState]
    public IParserState LastParserState { get; set; }

    [HelpOption(HelpText = "Display this Help Screen")]
    public virtual string GetUsage();
    public bool ParseCommandLine(string[] Args);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions, bool EnableMutuallyExclusive);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions, bool EnableMutuallyExclusive, bool UseCaseSensitive);
}

为此应用程序创建应用程序命令行类

public class ApplicationCommandLine : CommandLineOptions
{
    [Option('d', "download", HelpText = "Download Items before running")]
    virtual public bool Download { get; set; }

    [Option('g', "generate", HelpText = "Generate Mode (Generate New Test Results)", MutuallyExclusiveSet = "Run-Mode")]
    virtual public bool GenerateMode { get; set; }

    [Option('r', "replay", HelpText = "Replay Mode (Run Test)", MutuallyExclusiveSet = "Run-Mode")]
    virtual public bool ReplayMode { get; set; }
}

主程序:

ApplicationCommandLine AppCommandLine = new ApplicationCommandLine();

try
{
    // Parsers and sets the variables in AppCommandLine
    if (AppCommandLine.ParseCommandLine(args))
    {
        // Use the Download option from the command line.
        if (AppCommandLine.Download) { 
            DataFileDownload();
        }
        if (AppCommandLine.GenerateMode) { 
            GenerateProcessingData();
        }

        ...

    }
}

catch (Exception e)
{
    ...
}