0 Comments

If you create a  custom C# console application and want it to use parameters, you must create a command line parser to covert the command line parameters to C# variables.

There are many different ways to pas parameters to a custom C# console application like:

  • MyConsoleApp.exe –Parameter1Name “Parameter1Value” –Parameter2Name “Parameter2Value”
  • MyConsoleApp.exe “Parameter1Value”,”Parameter2Value”
  • MyConsoleApp.exe Parameter1Name=”Parameter1Value” Parameter2Name=”Parameter2Value”
  • etc.

 

In mine C# console applicaiton I used the format MyConsoleApp.exe Parameter1Name=”Parameter1Value” Parameter2Name=”Parameter2Value”.

To get a specific parameter from the args array, you can use:

 

Usage

var parser = new CommandLineParser();
string parameter1Value = parser.GetValue<string>("Parameter1Name", args);

 

 

Class

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace ADAICT
{
    public class CommandLineParser
    {
        private const string _keyValueSeperator = "=";

        public T GetValue<T>(string key, string[] args)
        {
            if(string.IsNullOrEmpty(key))
            {
                throw new NullReferenceException("Parameter [key] can't be null or empty");
            }
            if (args == null)
            {
                throw new NullReferenceException("Parameter [args] can't be null or empty");
            }

            // Select all keyvalue pairs with the given key
            var keyValuePairs = from a in args
                      where !string.IsNullOrEmpty(a) && a.Trim().StartsWith(key + "=")
                      select a.Trim();

            if (keyValuePairs.Count() > 0)
            {
                // Get last keyvalue pair with the given key
                var lastKeyValuePair = keyValuePairs.Last();
                
                // Get the value from the last keyvalue pair with the given key
                var value = this.GetValueFromKeyValuePair(lastKeyValuePair);

                // Convert the value to the return type
                var converter = TypeDescriptor.GetConverter(typeof(T));
                return (T)converter.ConvertFromString(value);
            }
            else
            {
                throw new Exception(string.Format("The key [{0}] can't be found on the commandline, make sure it is supplied on the commandline and there are no spaces between the key and the equalsign. Key is case sensitive!",key));
            }
        }
        public string GetValueFromKeyValuePair(string keyValuePair)
        {
            var result = string.Empty;

            if(!string.IsNullOrEmpty(keyValuePair))
            {
                // Split line on "="
                string[] keyValue = keyValuePair.Split(new string[] { _keyValueSeperator }, StringSplitOptions.RemoveEmptyEntries);

                if (keyValue.Length >= 2)
                {
                    // Restore the "=" in the value
                    result = String.Join(_keyValueSeperator, keyValue, 1, keyValue.Length - 1);
                }
                else
                {
                    if (keyValue.Length == 1)
                    {
                        // value does not contain a "="
                        result = keyValue[0];
                    }
                }

                // Remove leading and trailing quotes
                result = result.Trim(new char[] {'"'});
            }

            return result;
        }
    }
}

One Reply to “A little command line parser in C#

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts