Search code examples
c#perlcommand-line-argumentslong-integergetopt

C# equivalent to Perl's Getopt::Long


I am working on converting some old Perl scripts to C#, and I need to keep the functionality basically the same. In order to do this I need to parse the command line similarly to how Perl's Getopt::Long works, but I am having difficulty figuring out how to do this. I would greatly appreciate it if anyone could let me know a good way of doing this or point me in the direction of a good reference.


Solution

  • Jonathon Pryor wrote mono.Options with just that same motivation, as illustrated in his blog post: http://www.jprl.com/Blog/archive/development/mono/2008/Jan-07.html

    I have used it on a couple of projects, keeping all the attribution comments, and just throwing the file in my project directory. Works great for me.

    Here's me working with it:

    string iniFilePath = null;
    
    OptionSet os = new OptionSet()
        { { "ini="
          , "Valid path to an ini file."
          , (s) => { iniFilePath = s; }
          } };
    List<string> extra;
    try  {
        extra = os.Parse( Application.CommandLineArguments );
        return iniFilePath;
    }
    catch ( OptionException oex ) {
        Library.ExceptionHandler.handle( oex );
    }
    return null;