Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read csv file in vb.net

Tags:

csv

vb.net

I use this code in vb.net for reading in csv files:

filename = TextBox1.Text
        FileOpen(1, filename, OpenMode.Input)

        'first row contains header information, therefore read it in, but ignore it
        dummy = LineInput(1)

        While Not EOF(1)

            Input(1, dialcode)
            Input(1, chargecode)
            Input(1, description)
            Input(1, mincharge)
            Input(1, onpeak)
            Input(1, offpeak)
            Input(1, weekendonpeak)
            Input(1, weekendoffpeak)
            Input(1, onpeakconnect)
            Input(1, offpeakconnect)
            Input(1, weekendonpeakconnect)
            Input(1, weekendoffpeakconnect)
End While

this work fine

but i now have a different CSV to read in, and it has a , at the end of each line when i open the CSV file in notepad, so its not reading each row in because vb.net is unsure when a row ends

like image 435
user2710234 Avatar asked Feb 19 '26 14:02

user2710234


1 Answers

.Net has a built in CSV reader in the TextFieldParser. It will handle things like extra commas or quoted delimiters for you. For example, you could do this:

Dim dialcode As String
Dim chargecode As String
Dim mincharge As String

Dim tfp As New TextFieldParser("Z:\temp\test.csv")
tfp.Delimiters = New String() {","}
tfp.TextFieldType = FieldType.Delimited


tfp.ReadLine() ' skip header
While tfp.EndOfData = False
    Dim fields = tfp.ReadFields()
    dialcode = fields(0)
    chargecode = fields(1)
    mincharge = fields(2)
    Console.WriteLine(String.Format("{0} - {1} - {2}", dialcode, chargecode, mincharge))
End While
like image 128
John Koerner Avatar answered Feb 21 '26 03:02

John Koerner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!