Saturday, July 28, 2007

Importing/process a CSV File in VB.NET

Some us developers love doing is data imports :P Even more so when it's CSV or worse still, fixed length fields!! :P Thank goodness VB.NET gives us the StreamReader which allows us to open a file with a single line of code, thanks to the constructor overload. This also allows us to trip through the file line by line by calling the read method and also returning False when it is EOF!! What's more we have the split function on the string to chop it up on any delimiter of our choice and push it into an array!! What more could we ask for! So here is the code snippet:
Dim sr As New System.IO.StreamReader("mycsv.csv")

Do While sr.Peek <> -1
Dim myflds() As String
Dim myline As String
myline = sr.ReadLine
myflds = myline.Split(",")
' now you have every field in a sep element array
' Push them into a db, whatever

Loop

2 comments:

Jared said...

Out of curiosity, what would be your approach if the CSV file had the strings encapsulated in quotes?

Karl Davies-Barrett said...

THe split will ignore the quotes and so they will not effect the field splitting. You could try splitting on "','" or else you could just run a clean up routine on the array after the split. i.e to remove the first and last quote.