Friday, December 16, 2011

.NET CSV open source read write library

Yesterday I was in the need of write a lot of data exports in CSV (comma separated values) format.
To write a CSV-writer by my self should not be a big deal, but, you know, to write, to test, to fix (and go on) a common problem, that for sure has been solved, is not too wise.
So I googled a bit and finally find a very good CSV library, CvsHelper, hosted on GitHub and written by Josh Close in C#.
CvsHelper is very well written, it have a NUnit test project and have a lot of features.
One of them I like a lot, is the possibility to write a CsvClassMap for your business class, with your map logic, in a way very similar to the ClassMap of FluentNHibernate or the loquacius mapping by code of NHibernate 3.2.
Here an example:

  public sealed class MyClassMap : CsvClassMap<MyClass>
  {
     public MyClassMap()
     {
        int i = -1;
        Map(a => a.Id).Index(++i).Name("Id");
        Map(a => a.MyProperty).Index(++i).Name("My Prop in CSV");
        Map(a => a.MyProperty2).Index(++i).Name("My Property 2");
     }
  }

There is also a way to do a map with attributes, but to be honest, I don't like it (I prefer to have classes more decoupled possible).

Another feature is the possibility to define and use a custom TypeConverter (example in the source file linked below).

Of course you can write any sort of custom csv file you like, the library will take care about the correct csv format.

Here there is an example with many possibility usage.

Happy coding! :-)