Click here to Skip to main content
15,885,881 members
Articles / Programming Languages / C# 4.0

Intelligent Command Line Parser

Rate me:
Please Sign up or sign in to vote.
4.90/5 (27 votes)
29 May 2012CPOL4 min read 38.3K   1K   83  
Parses command line arguments and converts them into objects for use in your application
namespace CommandLineParser
{
    using System;

    /// <summary>
    /// Class for converting arguments to objects
    /// </summary>
    public class ObjectSerialiser
    {
        /// <summary>
        /// Sets the value for the appropriate property in the Argument Definition.
        /// </summary>
        /// <param name="map">The argument map.</param>
        /// <param name="argument">The argument.</param>
        /// <param name="arguments">The argument definition.</param>
        public static void SetValue(ArgumentMap map, Argument argument, IArgumentDefinition arguments)
        {
            var property = map.Property;
            Type t = property.PropertyType;

            property.SetValue(arguments, ConvertFromString(argument.Value, t), null);
        }

        /// <summary>
        /// Converts an object from a string.
        /// </summary>
        /// <param name="s">The value string to convert.</param>
        /// <param name="t">The type of the expected object.</param>
        /// <returns>The converted object</returns>
public static object ConvertFromString(string s, Type t)
{
    if (t.IsEnum)
    {
        return Enum.Parse(t, s);
    }

    // boolean accepts argument values of true, True, false, False, 1, 0
    if (t == typeof(bool))
    {
        // If type is bool with null or empty value return true
        if (string.IsNullOrWhiteSpace(s))
        {
            return true;
        }

        bool b;
        if (bool.TryParse(s, out b))
        {
            return b;
        }

        int i = Convert.ToInt32(s);

        if (i < 0 || i > 1)
        {
            throw new FormatException("Invalid boolean type. Must be 0 or 1.");
        }

        return Convert.ToBoolean(i);
    }

    return Convert.ChangeType(s, t);
}
    }
}

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
Software Developer (Senior) Performance Web
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions