Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

XGetoptCS - A Unix-style getopt() written in C#

0.00/5 (No votes)
5 Jun 2007 1  
XGetoptCS provides Unix-style command line processing for C# apps

Introduction

XGetoptCS is a port of my C++ XGetopt to C#. XGetoptCS is modeled after the Unix getopt() function. The basic idea is that you call the XGetoptCS method Getopt() in a loop like this:

static int Main(string[] args)
{
    char c;
    XGetopt go = new XGetopt();
    while ((c = go.Getopt(args.Length, args, "aBn:")) != '\0')
    {
        switch (c)
        {
            case 'a':
                Console.WriteLine("option -a");
                break;

            case 'B':
                Console.WriteLine("option -B");
                break;

            case 'n': 
                Console.WriteLine("option -n with arg '{0}'", go.Optarg);
                break;

            case '?':
                Console.WriteLine("illegal option or missing arg");
                return 1;
        }
    }

    if (go.Optarg != string.Empty)
        Console.WriteLine("non-option arg '{0}'", go.Optarg);

    ...

    return 0;
}

Getopt will continue processing the command line arguments until it hits the end (returns a '\0') or finds an illegal option (returns a '?'). In the above example, the option string "aBn:" contains the three legal options: -a, -B (options are case sensitive), and -n. There is a colon (:) after the -n option, indicating that it must be followed by a value. This value string may be retrieved by using the Optarg property. See the XGetopt.cs module header for more details.

XGetoptCS Demo

So here is my version of Getopt() for C#. Please note it does not have all features of the latest GNU getopt() - the limitations are documented in the source header. How to use it is pretty straightforward if you are already familiar with Posix or Unix getopt().

The demo project provides a sample app that shows how command line is processed:

screenshot

How To Use

To integrate XGetopt into your own app, add XGetopt.cs to your project, and add the line:

using XGetoptCS;
to the file where you want to call Getopt(). See demo code in Program.cs for example.

Revision History

Version 1.0 � 2007 June 5

  • Initial public release

Usage

This software is released into the public domain. You are free to use it in any way you like, except that you may not sell this source code. If you modify it or extend it, please consider posting new code here for everyone to share. This software is provided "as is" with no expressed or implied warranty. I accept no liability for any damage or loss of business that this software may cause.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here