O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required