C# CSV Import

An old topic, I agree. Unfortunately we still can’t forget about CSV files and I see so many questions popping up on forums and especially on my blog related to this topic. Not every company features APIs or XML files yet, so it’s always nice to be comfortable with CSV Readers or Libraries.

First of all: Don’t write your own CSV Parser! No matter if it’s a C# CSV Import or VB.NET. There are so many libraries, frameworks, etc. – you really don’t have to reinvent the wheel once again. It’s not just about using String.Split(“,”), you need to care for much more nasty stuff. Fortunately other people already went through the headaches for you!

So what to do? Use FileHelpers Library 2.0! Instead of calling array items by writing myarray[3] you can even use e.g. mycart.ID now, isn’t that beautiful? Here’s a little code example:

FileHelperEngine engine = new FileHelperEngine(typeof(AdRow));
    AdRow[] res = engine.ReadFile(filename) as AdRow[];       
    foreach (AdRow ar in res)
    {           
        Response.Write(ar.CartItem + "<br />");                          
    }

It won’t get easier than that. I use it in several ASP.NET Projects and best of all: It’s free! Check it out and thanks to Marcos for creating it: FileHelpers 2.0. You will find tons of examples for reading and writing CSV Files.

3 comments ↓

#1 Mark Wisecarver on 08.17.08 at 6:15 pm

On one of my Migration projects at Siemens CSV proved the best method when moving records from Oracle to SQL Server programaticly.

#2 Travis James on 08.18.08 at 4:20 am

It seems that FileHelpers, which is quite cool in concept, misses the mark in implementation by not providing attributes that work on object properties as well as public object fields.

#3 andreas.kraus on 08.25.08 at 8:04 am

Mark: I’d really prefer XML these days, but I would agree if it’s about moving data between or for older DBS.

Leave a Comment