This class will parse, organize and collect command line options. I couldn't find anything like it, so I wrote one. This works all the way down to .NET 1.1 if you are lucky enough to still be using that.
Save this as ArgDictionary.cs, change the namespace as needed, and feel free to use it in your projects.
using System; using System.Collections.Generic; namespace Utilities { ///TODO: Create a function that will output usage text./// Implements a Dictionary object for handling command line options. /// Supports options with prefixes -, --, or /. /// Supports Boolean, String, or Int32 option values. /// String options are in the following format: /// /stringOption value /// Int32 options are in the following format: /// /intOption 200 /// Boolean options are in the following format: /// /boolOption /// NOTE: if the Boolean option is present in the command line, it is true. /// /// Supports both a long and short version for each option (e.g. /a and /Account /// can be mapped to the same value). /// NOTE: When working with options in the code, always use the long version. /// NOTE: Options (short and long) are CASE SENSITIVE! unix4ever! /// ////// Program.exe /boolOption /stringOption value /int 200 /h /// /// static void Main(string[] args) /// { /// ArgDictionary options = new ArgDictionary(); /// try /// { /// options.AddBooleanOption("h", "help"); /// options.AddBooleanOption("boolOption"); /// options.AddStringOption("stringOption"); /// options.AddInt32Option("i", "int"); /// options.ParseOptions(args); /// } /// catch (Exception ex) /// { /// PrintError("Error with the command line options.", ex); /// Usage(); /// return; /// } /// } /// /// if (options.Count == 0 || options.ContainsKey("help")) /// { /// Usage(); /// return; /// } /// /// // Prompt for options the user may have forgotten /// if (!options.ContainsKey("accountId")) /// options.PromptForOption("accountId", typeof(String)); /// /// // Use the options in your program /// Int32 number = (Int32)options["int"]; /// Console.WriteLine("stringOption: " + (string)options["stringOption"]); /// } /// class ArgDictionary: Dictionary{ private Dictionary optionTypes; /// /// Maps short options to the long version (we want to use the long version in code for readability) /// private DictionaryoptionShortMap; public ArgDictionary() { optionTypes = new Dictionary (); optionShortMap = new Dictionary (); } #region Add methods public void Add(string option, Type type) { optionTypes.Add(option, type); } public void Add(string shortOption, string longOption, Type type) { if (shortOption != longOption) optionShortMap.Add(shortOption, longOption); optionTypes.Add(longOption, type); } public void AddStringOption(string option) { optionTypes.Add(option, typeof(String)); } public void AddStringOption(string shortOption, string longOption) { if (shortOption != longOption) optionShortMap.Add(shortOption, longOption); optionTypes.Add(longOption, typeof(String)); } public void AddBooleanOption(string option) { optionTypes.Add(option, typeof(Boolean)); } public void AddBooleanOption(string shortOption, string longOption) { if (shortOption != longOption) optionShortMap.Add(shortOption, longOption); optionTypes.Add(longOption, typeof(Boolean)); } public void AddInt32Option(string option) { optionTypes.Add(option, typeof(Int32)); } public void AddInt32Option(string shortOption, string longOption) { if (shortOption != longOption) optionShortMap.Add(shortOption, longOption); optionTypes.Add(longOption, typeof(Int32)); } #endregion Add methods #region Option parsing methods /// /// Parses the command line options. Accepts options with the following prefixes: /// - -- / /// ////// options.ParseOptions(args); /// /// The command line arguments public void ParseOptions(string[] args) { int i = 0; string option = string.Empty; string optionIn = string.Empty; // NOTE: this is ONLY for friendlier error messages if there is a problem with the option Type type = typeof(String); while (i < args.Length) { option = args[i]; option = option.TrimStart(new char[] { '-', '/' }); // Accept parameters in format -param --param or /param optionIn = option; i++; // Get the short version if this is long if (optionShortMap.ContainsKey(option)) option = optionShortMap[option]; if (!optionTypes.ContainsKey(option)) throw new ArgumentException("Invalid Option Found: " + optionIn, optionIn); type = optionTypes[option]; if (type == typeof(String)) { this.Add(option, args[i]); i++; } else if (type == typeof(Boolean)) { this.Add(option, true); } else if (type == typeof(Int32)) { string intOption = args[i]; i++; try { this.Add(option, Int32.Parse(intOption)); } catch (Exception ex) { throw new ArgumentException("Unable to parse Int32 Option: " + optionIn + " " + intOption, optionIn, ex); } } else { throw new ArgumentException("We don't support that type: " + optionIn, optionIn); } // if (type == } // while } ////// Allows you to prompt the user for an option at runtime. /// ////// options.PromptForOption("accountId", typeof(String)); /// /// This will print the following to the console: /// /// accountId: /// /// Name of the option (long version) /// Option Type public void PromptForOption(string option, Type type) { Console.Write(option + ": "); string optionValue = Console.ReadLine(); if (type == typeof(String)) { this.Add(option, optionValue); } else if (type == typeof(Boolean)) { this.Add(option, true); } else if (type == typeof(Int32)) { try { this.Add(option, Int32.Parse(optionValue)); } catch (Exception ex) { throw new ArgumentException("Unable to parse Int32 Option: " + option + " " + optionValue, option, ex); } } else { throw new ArgumentException("We don't support that type: " + option, option); } // if (type == } #endregion Option parsing methods } }
Comments
Post a Comment