Jul 272011

In last post I wen’t through task of restoring properties from their textual representation. But how did we end up with text?

It is as simple as loop through all public properties and then using TypeConverter in order to properly convert a value to it’s string representation. Do notice that ConvertToInvariantString is preferred over ConvertToString in order for code to properly work on non-USA Windows.

public static IDictionary<string, string> GetPairs(object objectInstance) {
    var result = new Dictionary<string, string>();
    foreach (var propertyInfo in objectInstance.GetType().GetProperties()) {  //loops through all public properties
        var propertyConverter = TypeDescriptor.GetConverter(propertyInfo.PropertyType);  //gets converter for property
        var stringValue = propertyConverter.ConvertToInvariantString(propertyInfo.GetValue(objectInstance, null));  //converts value to string
        result.Add(propertyInfo.Name, stringValue);
    return result;

P.S. Saving key/value pairs to file is not shown here… guess how it is done… :)

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>