Wednesday, October 26, 2005

RE: Yet another command line parsing system

This looks like a logical way to handle command line parameters while still following convention of using an app.config file.

....I used another arguments parser from Code Project, "C#/.NET Command Line Arguments Parser".
I like it because it works like the ASP.NET querystring parser - it handles the parsing (quoted strings, different delimiter styles) and exposes a string dictionary with the results.


I use a GetSettings accessor that reads the default from the app.config file, but allows overrides via command line. I like this approach because settings are their standard location (app.config), and any config setting can be overriden via command line without an attribute change and a recompile.


[STAThread]
private static int Main(string[] args)
{
    Processor processor1 = 
new Processor(args);
    
return processor1.Process();
}

private Arguments arguments;

public Processor(string[] args)
{
    
this.arguments = new Arguments(args);
}

public Process()
{
    Console.WriteLine(
this.GetSetting("PreventEvil"));
}

private string GetSetting(string key)
{
    
string setting = string.Empty;
    
if (this.arguments[key] != null)
    {
        setting = 
this.arguments[key];
    }
    
else
    
{
        setting = ConfigurationSettings.AppSettings.Get(key);
    }
    
if (setting == null)
    {
        
return string.Empty;
    }
    
return setting;
}


[via [JonGalloway.ToString()]]

2 comments:

  1. NConsoler is an open source library that provides command line parser functionality based on attribute metadata attached to type.
    Library is very easy to add and use in your application. NConsoler gives an ability to display help and validation messages without any line of code.

    http://nconsoler.csharpus.com/

    Example code:

    using System;
    using NConsoler;

    public class Program {
    public static void Main(params string[] args) {
    Consolery.Run(typeof(Program), args);
    }

    [Action]
    public static void Method(
    [Required] string name,
    [Optional(true)] bool flag) {
    Console.WriteLine("name: {0}, flag: {1}", name, flag);
    }
    }

    and use it:

    program.exe "Maxim" /-flag

    ReplyDelete
  2. NConsoler looks pretty easy to use. What I liked about Jon Galloway's approach was that it worked as an override to the app.config file.

    ReplyDelete

Note: Only a member of this blog may post a comment.