Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

read csv file in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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:empest.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...