-3

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    does this help? http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c – stevieb Jun 23 '16 at 14:07
  • 3
    Instead of saying "I need to do it the same as Perl's Getopt::Long," which I'm guessing most C# programmers have never seen before, it would be better to give an example of the command line arguments you need to parse and to explain the functionality you're having trouble reproducing. – ThisSuitIsBlackNot Jun 23 '16 at 14:12
  • Can you explain by giving an example on how it works? – Raktim Biswas Jun 23 '16 at 14:16
  • 1
    @Rakitić, An example is not going to be very useful. At the core, it supports `-f`/`--foo` and `-f=arg`/`--foo arg` (where the argument may be optional or required). But it supports far far more. It supports `--`. It supports bundling (configurable). It can check if the option argument is a number. It supports callbacks triggered on the presence of options. It supports negation of argumentless options using `no-`. It supports arrays (e.g. `--foo a --foo b` => `[a,b]`). It supports pass-through of unrecognized options (configurable). It supports alternate option prefixes (e.g. `+foo`) ...... – ikegami Jun 23 '16 at 14:42

1 Answers1

2

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;
Axeman
  • 29,660
  • 2
  • 47
  • 102