Promote Your Blog

Friday, March 2, 2012

How To Read A .csv File

Suppose I have .csv (Comma Separated values) file and I need to read certain columns of this file and plot them (related post: using .NET Chart Control). So, here is the code to read .csv files:

Imports System.IO.FileInfo

Imports System.IO

Dim x As Double, y1 As Double, y2 As Double

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(fn) 'fn =.csv File name

MyReader.TextFieldType = FileIO.FieldType.Delimited


Dim currentRow As String()

Dim i As Integer

Dim j As Integer

j = 0

x = 0.0

While Not MyReader.EndOfData


currentRow = MyReader.ReadFields()

Dim currentField As String

If j <> 0 Then ‘Skipping Header Row

i = 0

For Each currentField In currentRow

If i = 0 Then ‘First column

x = currentField

ElseIf i = 4 Then ‘Fifth column

y1 = currentField

ElseIf i = 5 Then

y2 = currentField

End If

i = i + 1


‘Do the operation on retrieved values. E.g. plotting them using .Chart Control (see relevant post)

x = x + 1

End If

j = j + 1

Catch ex As Microsoft.VisualBasic.


MsgBox("Line " & ex.Message &

"is not valid and will be skipped.")

End Try

End While

End Using

No comments:

Post a Comment