Click here to Skip to main content
15,895,557 members
Articles / Programming Languages / XML

C#/.NET Command Line Argument Parser Reloaded

Rate me:
Please Sign up or sign in to vote.
4.86/5 (32 votes)
28 Sep 2020CPOL3 min read 106.8K   1.9K   128  
Easy to use yet powerful command line argument parser which also creates usage and parameter information for the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.Collections;
using System.Globalization;

namespace CLAParserTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //nationalized output is not wanted. make it all english.
            System.Globalization.CultureInfo MyCulture = new System.Globalization.CultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentCulture = MyCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = MyCulture;

            //initialize CommandLineArgumentParser and set up parameters.
            CLAParser.CLAParser CmdLine = new CLAParser.CLAParser("CLAParserTest");
            CmdLine.ParameterPrefix = "/";

            bool UseMathExample = false;
            if (UseMathExample)
            {
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "output", CLAParser.CLAParser.ValueType.OptionalString, "Write output to file, if no file specified default file output.txt is used.");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Required, "add", CLAParser.CLAParser.ValueType.MultipleInts, "Do a mathematical addition of number given integers.");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "v", CLAParser.CLAParser.ValueType.MultipleBool, "Activate verbose output, multiple " + CmdLine.ParameterPrefix + "v increase verbosity even more.");
            }
            else
            {
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "ConnectionString", CLAParser.CLAParser.ValueType.String, "no help");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "Scriptfile", CLAParser.CLAParser.ValueType.String, "no help");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Required, "", CLAParser.CLAParser.ValueType.String, "filename");
                //CmdLine.AllowAdditionalParameters = true;
            }

            //do command line parsing, if exception caught display it and show usage information to user.
            try
            {
                CmdLine.Parse();
            }
            catch (CLAParser.CLAParser.CmdLineArgumentException Ex)
            {
                Console.WriteLine(Ex.Message);
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetUsage());
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetParameterInfo());
                if (System.Diagnostics.Debugger.IsAttached)
                    Console.ReadKey();
                return;
            }

            //do what has to be done by program.
            if (CmdLine.Count != 0) //if there is a required parameter found, this if is not necessary.
            {
                int verbose = 0;
                string output_string = "";
                string output_file = null;

                if (CmdLine["v"] != null)
                {
                    verbose = Convert.ToInt32(CmdLine["v"]);
                    output_string += "Verbose output at level: " + CmdLine["v"] + "\r\n";
                }
                if (CmdLine["output"] != null)
                {
                    if (verbose > 0) output_string += CmdLine.ParameterPrefix + "output paramater found.\r\n";
                    if (CmdLine["output"] == "")
                    {
                        output_file = "output.txt";
                        if (verbose > 2) output_string += "Default output file is used.\r\n";
                    }
                    else { output_file = CmdLine["output"]; }
                    if (verbose > 1) output_string += "Output file is: " + output_file + "\r\n";
                }
                if (CmdLine["add"] != null)
                {
                    if (verbose > 0) output_string += CmdLine.ParameterPrefix + "add paramater found.\r\n";
                    int result = 0;
                    System.Text.RegularExpressions.Regex Split = new System.Text.RegularExpressions.Regex("[\\s]+");
                    string[] numbers = Split.Split(CmdLine["add"]);
                    foreach (string n in numbers)
                    {
                        if (verbose > 1) output_string += "Adding " + n + " to result.\r\n";
                        result += Convert.ToInt32(n);
                        if (verbose > 2) output_string += "Intermediate result now: " + result.ToString() + "\r\n";
                    }
                    output_string += "Result of addition is: " + result.ToString() + "\r\n";
                }

                if (verbose > 3)
                {
                    output_string += "Listing of all arguments and their values:\r\n";
                    foreach (DictionaryEntry arg in CmdLine)
                    {
                        output_string += "Argument: \"" + arg.Key + "\" -> Value: \"" + arg.Value + "\"\r\n";                        
                    }
                    
                }

                Console.Write(output_string);
                if (output_file != null)
                {
                    try
                    {
                        System.IO.File.WriteAllText(output_file, output_string);
                        if (verbose > 0)
                            Console.Write("Output file written.");
                    }
                    catch (Exception Ex)
                    {
                        Console.Write("Exception while writing output file: " + Ex.Message);
                    }

                }
            }
            else
            {
                Console.WriteLine(CmdLine.GetUsage());
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetParameterInfo());
            }

            if (UseMathExample==false)
            {
                IEnumerator e = CmdLine.GetEnumerator();
                while (e.MoveNext())
                {
                    DictionaryEntry arg = (DictionaryEntry)e.Current;
                    Console.WriteLine(arg.Key + "=" + arg.Value);
                }
            }

            if (System.Diagnostics.Debugger.IsAttached)
                Console.ReadKey();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions