Comma Delimited Text File

Jynx

Active member
Joined
Oct 20, 2007
Messages
44
Programming Experience
Beginner
I'm having some trouble. I have a file who's contents are :

"Bob Jones", 1, "A-", "Introduction to CS"
"Sarah Johnson", 2, "B+", "Data Structures"
"Sam Smith", 3, "A", "Visual Basic"

I'm not sure how to read this file and have it display as :

Bob Jones 1 A- Introduction to CS
Sarah Johnson 2 B+ Data Structures
Sam Smith 3 A Visual Basic

As you can see, I'm really floundering around with the below code.

VB.NET:
Imports System.IO 
Public Class Form1 
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
 
        Dim fileName As String 
        fileName = ("D:\Data.txt") 
        If File.Exists(fileName) Then 
            Try 
                Dim stream As New StreamReader(fileName) 
                Dim sLine As String = stream.ReadLine 
 
                While Not sLine Is Nothing 
                    stream.ReadLine.Split(","c) 
                    txtOutput.Text = stream.ReadLine 
 
                    sLine = stream.ReadLine() 
                End While 
 
            Catch ex As System.IO.IOException 
                MessageBox.Show("Error reading from file", "File Error", _ 
                   MessageBoxButtons.OK, MessageBoxIcon.Error) 
            End Try 
        End If 
    End Sub
 
Ok so I did this. However, it only displays the first line, and it adds that row on separate lines. So where as I want :

Bob Jones 1 A- Introduction to CS
Sarah Johnson 2 B+ Data Structures
Sam Smith 3 A Visual Basic

It instead gives me :

Bob
Jones
1
A-
Introduction
To
CS

VB.NET:
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Me.LoadCommaDelimetedTextFileIntoListBox("D:\Data.txt")

    End Sub


    Private Sub LoadCommaDelimetedTextFileIntoListBox(ByVal filePath As String)

        ' Declare a variable named theTextFieldParser of type TextFieldParser.
        Dim theTextFieldParser As FileIO.TextFieldParser

        ' Call the My feature's OpenTextFieldParser method passing in a file path.
        ' Assign the resulting TxtFileParser object to theTextFieldParser variable.
        theTextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(filePath)

        ' Set TextFieldParser object's TextFieldType property to Delimited.
        theTextFieldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited

        ' Configure delimiters to handle a comma delimited text file:
        ' Set TextFieldParser object's Delimiter's property to a string array
        ' containing one element with the value ",".
        theTextFieldParser.Delimiters = New String() {","}

        ' Declare a variable named currentRow of type string array.
        Dim currentRow() As String

        ' While the end of file has not been reached....
        While Not theTextFieldParser.EndOfData
            Try
                ' Read the fields on the current line
                ' and assign them to the currentRow array variable.
                currentRow = theTextFieldParser.ReadFields()

                ' Declare a variable named currentField of type String.
                Dim currentField As String

                ' Use the currentField variable to loop
                ' through fields in the currentRow.
                For Each currentField In currentRow
                    ' Add the the currentField (a string)
                    ' to the demoLstBox items.
                    Me.demoListBox.Items.Add(currentField)
                Next
            Catch malFormLineEx As Microsoft.VisualBasic.FileIO.MalformedLineException
                MessageBox.Show("Line " & malFormLineEx.Message & "is not valid and will be skipped.", "Malformed Line Exception")
            Catch ex As Exception
                MessageBox.Show(ex.Message & " exception has occurred.", "Exception")
            Finally
                ' If successful or if an exception is thrown,
                ' close the TextFieldParser.
                theTextFieldParser.Close()
            End Try
        End While


    End Sub
 
Well, look at how you're displaying the data:
VB.NET:
                For Each currentField In currentRow
                    ' Add the the currentField (a string)
                    ' to the demoLstBox items.
                    Me.demoListBox.Items.Add(currentField)
                Next
You're adding each field separately. If you don't want each field to be separate then you can't do that. You have to join them all together first, then you add the result once and once only.
 
Well, I've done some extra work. This works fine and it seems to produce the cleanest results. However I'm having trouble removing the "" parenthesis. I've removed the commas fine. I'm also having a very difficult time writing to the file with the commas and parenthesis.

I have 5 text box's for First Name, Last Name, ID, Grade, Class. That I need to write to the file as : "Bob Jones", 1, "A-", "Introduction to CS"


VB.NET:
Imports System.IO
Public Class Form1

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        With ListView1
            Dim Lines(.Items.Count) As String
            Dim I, J As Integer
            Lines(0) = .Columns(0).Text
            For J = 1 To .Columns.Count - 1
                Lines(0) += "," & .Columns(J).Text
            Next
            For I = 1 To .Items.Count
                Lines(I) = .Items(I - 1).Text
                For J = 1 To .Columns.Count - 1
                    Lines(I) += "," & .Items(I - 1).SubItems(J).Text
                Next
            Next
        End With
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim FileLines() As String = File.ReadAllLines("D:\Data.txt")
        With ListView1
            .SuspendLayout()
            .View = View.Details
            .Columns.Clear()
            .Items.Clear()
            .Scrollable = True

            Dim I, J, TextWidth As Integer
            Dim Lines(FileLines.Length - 2)() As String
            Dim Headers() As String = FileLines(0).Split(","c)
            Dim Fields As Integer = Headers.Length
            Dim MaxWidth(Fields - 1) As Integer
            For J = 0 To Fields - 1
                TextWidth = TextRenderer.MeasureText(Headers(J), .Font).Width + 40
                If TextWidth > MaxWidth(J) Then MaxWidth(J) = TextWidth
            Next
            For I = 0 To Lines.Length - 1
                Lines(I) = FileLines(I + 1).Split(","c)
                For J = 0 To Fields - 1
                    TextWidth = TextRenderer.MeasureText(Lines(I)(J), .Font).Width + 40
                    If TextWidth > MaxWidth(J) Then MaxWidth(J) = TextWidth
                Next
            Next
            .Width = 0
            For J = 0 To Fields - 1
                .Columns.Add(Headers(J), MaxWidth(J), HorizontalAlignment.Left)
                .Width += MaxWidth(J)
            Next
            .Width += 4
            For I = 0 To Lines.Length - 1
                .Items.Add(Lines(I)(0))
                For J = 1 To Fields - 1
                    .Items(I).SubItems.Add(Lines(I)(J))
                Next
            Next
            .ResumeLayout()
        End With
    End Sub
End Class
 
Those are double quotes. () are parentheses. One parenthesis, more than one parentheses. If you'd stuck with what I suggested it wouldn't bre an issue because both ADO.NET and the TextFieldParser will remove the double quotes automatically. If you want to do it manually then the String.Trim method will remove specific characters from the beginning and end of a string. That may be dangerous though, because a string that actually contains double quotes will then be read incorrectly. Of course, ADO.NET and the TextFieldParser handle that automatcally too.
 
Back
Top