Csvhelper: Update Documentation for ConvertUsing Only Works on Reads

Created on 11 May 2017  路  7Comments  路  Source: JoshClose/CsvHelper

Can the documentation at joshclose.github.io/CsvHelper on ConvertUsing be updated to mention it only works on reading, not writing? Is this page in the repo? Perhaps I can submit a PR for it?

Source

Thanks,
Mike D.

documentation

Most helpful comment

thanks Josh!

All 7 comments

Is there alternative for writting?

Currently, no. I would think it would be useful consider it is for reading.

I currently (CsvHelper 2.x) use this workaround:

    public static CsvPropertyMap UsingExpression<T>(this CsvPropertyMap map, Func<string, T> readExpression,
            Func<T, string> writeExpression)
        {
            return map.TypeConverter(new ExpressionConverter<T>(readExpression, writeExpression));
        }
    public class ExpressionConverter<T> : ITypeConverter
    {
        public ExpressionConverter(Func<string, T> readExpression, Func<T, string> writeExpression)
        {
            _ReadExpression = readExpression;
            _WriteExpression = writeExpression;
        }

        private Func<string, T> _ReadExpression { get; set; }
        private Func<T, string> _WriteExpression { get; set; }

        public bool CanConvertFrom(Type type)
        {
            return type == typeof(string);
        }

        public bool CanConvertTo(Type type)
        {
            return type == typeof(string);
        }

        public object ConvertFromString(TypeConverterOptions options, string text)
        {
            return _ReadExpression(text);
        }

        public string ConvertToString(TypeConverterOptions options, object value)
        {
            return _WriteExpression((T) value);
        }
    }

example using Option for property "ColumnName" (using another great lib: https://github.com/louthy/language-ext)

Map(m => m.ColumnName).UsingExpression(parseInt, oi => oi.Match(i => i.ToString(), () => ""));

parseInt is the readExpression (reads raw string and returns Option)

oi => oi.Match(i => i.ToString(), () => "") is the writeExpression (turns Option into string representation)


My current problem is: this does not work in 3.x anymore. @JoshClose: Is there some replacement?
A ConvertUsing with both directions would be fine.

There is a ConvertUsing overload for writing now in 3.0. I don't remember if I've released it to NuGet yet though. I can check later when I get to a computer

I just pushed a new pre-release version to nuget. This is the commit that adds ConvertUsing for writing. https://github.com/JoshClose/CsvHelper/commit/e40570fb314af1af1bf2b598695c6e0bff234594

I'm closing this since it doesn't apply anymore.

thanks Josh!

Was this page helpful?
0 / 5 - 0 ratings