3.23. Parsing Command-Line Parameters

Problem

You require your applications to accept one or more command-line parameters in a standard format. You need to access and parse the entire command line passed to your application.

Solution

Use the following class to help with parsing command-line parameters:

using System; using System.Diagnostics; public class ParseCmdLine { // All args are delimited by tab or space // All double-quotes are removed except when escaped '\"' // All single-quotes are left untouched public ParseCmdLine( ) {} public virtual string ParseSwitch(string arg) { arg = arg.TrimStart(new char[2] {'/', '-'}); return (arg); } public virtual void ParseSwitchColonArg(string arg, out string outSwitch, out string outArgument) { outSwitch = ""; outArgument = ""; try { // This is a switch or switch/argument pair arg = arg.TrimStart(new char[2] {'/', '-'}); if (arg.IndexOf(':') >= 0) { outSwitch = arg.Substring(0, arg.IndexOf(':')); outArgument = arg.Substring(arg.IndexOf(':') + 1); if (outArgument.Trim( ).Length <= 0) { throw (new ArgumentException( "Command-Line parameter error: switch " + arg + " must be followed by one or more arguments.", arg)); } } else { throw (new ArgumentException( "Command-Line parameter error: argument " + arg + " must be in the form of a 'switch:argument}' pair.", arg)); } } catch (ArgumentException ae) { // Re-throw the exception to be handled in the calling method throw; } catch (Exception e) { // Wrap an ArgumentException around the exception ...

Get C# Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.