Simple VB6 read and write converted to vb.net? How to Read CSV????

N

newsaboutgod

I think VB.NET drives some people crazy because some simple VB6 things
seem so hard.

Here is some VB6 code:

'Write CSV File
open "c:\test.csv" for output as #1
write#1, "1","2","3","4","5"
write#1, "1","2","3","4","5"
write#1, "1","2","3","4","5"
Close#1

'Read CSV File
open "c:\test.csv" for input as #1
input#1, A$,B$,C$,D$,E$
input#1, A$,B$,C$,D$,E$
input#1, A$,B$,C$,D$,E$
Close#1

Works perfect and real easy. I can also open up the file in excel.

In VB.NET I can write the file the same way with:

FileOpen(1, "c:\testfile2.csv", OpenMode.Output)
WriteLine(1, "1", "2", "3", "4")
WriteLine(1, "2", "2", "3", "4")
WriteLine(1, "3", "2", "3", "4")
FileClose(1)

Now, how can I easily read the file from VB.NET into variables???? It
is driving me crazy and there seems to be about 10 different ways but
I want a simple CSV read routine. THANKS for any help.

Sheila
 
G

Guest

Your VB6 reader has a built in assumption about the number of columns in a
row of data. For example, your code needs to change if you want more data.
In general I would read the lines into an array of lines with
File.ReadAllLines, then split each row into colums with the string.Split()
method. If you know there are a lot of lines, then maybe reading one line at
a time will suffice.
 
N

Number 11950 - GPEMC! Replace number with 11950

Sambantham Kuppusamy said:
vb.net is high Tech.

Is that sarcasm or an interesting variation on Ad Hominem (Ad Techinem?) ?

:^)

There's got to be a simpler way. What about "stream" reading. Also, people
have been writing header analysis routines for decades - I thought by now
header analysis would be implicit in any table reading
method/function/statement in a modern programming language...?
 
S

sergejusz

Hi,
I use this simple and convenient class.
============================================
Imports System.Collections.Generic
Imports System.IO

Public Class CSVParser

#Region "Local Variables"
Protected m_fields As New List(Of String)
Protected m_separator As String = String.Empty
Protected m_stream As System.IO.StreamReader = Nothing
Protected m_names As New Dictionary(Of String, Int32)
#End Region


#Region "Ctors"
Public Sub New(ByVal PathName As String, Optional ByVal
Separator As String = ",")
m_separator = Separator
If System.IO.File.Exists(PathName) Then
m_stream = New System.IO.StreamReader(PathName)
Else
Throw New Exception("File not found")
End If
End Sub
#End Region

#Region "Methods"
Public Sub Close()
m_stream.Close()
m_stream = Nothing
End Sub

Public Sub ResetNames()
m_names.Clear()
End Sub


' associate field with name
Public Sub SetName(ByVal index As Int32, ByVal FieldName As
String)
If FieldName.Length > 0 Then
If m_names.ContainsKey(FieldName) Then
Throw New Exception("Duplicate Name " & FieldName)
Else
m_names.Add(FieldName, index)
End If
Else
Throw New Exception("Empty Name Supplied")
End If
End Sub


Public Function ReadLine() As Boolean
m_fields.Clear()
If m_stream IsNot Nothing AndAlso Not m_stream.EndOfStream
Then
Dim buffer As String = m_stream.ReadLine()
If buffer.Length > 0 Then
Parse(buffer)
Return True
End If
End If
Return False
End Function


Protected Sub Parse(ByVal buffer As String)
m_fields.AddRange(buffer.Split(New String() {m_separator},
StringSplitOptions.None))
End Sub


Public Function Count() As Int32
Return m_fields.Count
End Function


' no out of range exceptions
Public Overloads Function GetValue(ByVal index As Int32) As
String
If index >= 0 AndAlso index < m_fields.Count Then
Return m_fields(index)
End If
Return String.Empty
End Function

Public Overloads Function GetValue(ByVal name As String) As
String
Dim index As Int32
If m_names.TryGetValue(name, index) Then
Return GetValue(index)
End If
Throw New Exception("Invalid Field Name " & name.ToUpper)
End Function
#End Region

End Class



Public Class CSVFNParser : Inherits CSVParser


#Region "Ctors"
Public Sub New(ByVal PathName As String, Optional ByVal
Separator As String = ",")
MyBase.New(PathName, Separator)
Initialize()
End Sub

Protected Sub Initialize()
If ReadLine() Then
Dim N As Int32 = 0
For Each s As String In m_fields
Dim FieldName As String = s.ToUpper
If m_names.ContainsKey(FieldName) Then
Throw New Exception("Duplicate Name " &
FieldName)
Else
m_names.Add(FieldName, N)
End If
N += 1
Next
End If
If m_names.Count = 0 Then
Throw New Exception("No Field Names in CSV")
End If
End Sub
#End Region

End Class

----------------------------------

And sample program:

Sub Main()

Dim csv As New CSVParser("C:\blablabla.csv", ",")
While csv.ReadLine()
Dim N As Int32 = csv.Count
Console.WriteLine("There are {0} fields in this line", N)
For j as Int32 = 0 To N-1
If csv.GetValue(j).Length > 0 Then
Console.WriteLine("[{0}]", csv.GetValue(j))
End If
Next

Console.WriteLine("---------------------------------------------------")
End While
Console.ReadLine()
End Sub

HTH
Serge
http://www.sergejusz.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top