user877806
user877806

Reputation: 1

Reading and writing specfic line from a text file

I have the same problem that Niphoet had in Stack Overflow question Overwrite a specific line in a text file using VB.NET.

I am trying to implement the code that Axarydax showed in C# that I am trying to translate to use into VB.NET. My problem is that the code will make my new text file, but it will not write any of the lines from the other text file to it and just leaves it blank. I think my problem is with the while loop statement, but I am not sure. Here is what I have so far:

 Private Sub submitButton_Click(ByVal sender As System.Object, ByVal e As       System.EventArgs) Handles submitButton.Click
    Dim trackname As String
    Dim fso
    fso = CreateObject("Scripting.FileSystemObject")
    trackname = TrackComboBox.Text
    Dim fileName As String = "C:\Papyrus\NASCAR3\tracks\" + trackname + "\" + trackname + ".txt"
    Dim newfile As String = "C:\Papyrus\NASCAR3\tracks\" + trackname + "\" + "copy.txt"
    If System.IO.File.Exists(fileName) Then

        Dim objReader As New System.IO.StreamReader(fileName, True)
        Dim objWriter As New System.IO.StreamWriter(newfile, False)
        Dim line
        'write back
        While (line = objReader.ReadToEnd() <> Nothing)
            If (line.StartsWith("RELS")) Then
                objWriter.WriteLine(relstTextBox.Text)
            Else
                objWriter.WriteLine(line)
            End If

        End While
        objReader.Close()
        objWriter.Close()
    Else
        MessageBox.Show("Could not find " + trackname + " track text file sucessfully")
    End If
End Sub

Upvotes: 0

Views: 1924

Answers (1)

Waqas
Waqas

Reputation: 6802

If you want to read your text file line by line then change your code to:

Dim line As String = ""

'Write back
line = objReader.ReadLine()
While Not line Is Nothing
    If (line.StartsWith("RELS")) Then
        objWriter.WriteLine(relstTextBox.Text)
    Else
        objWriter.WriteLine(line)
    End If

    line = objReader.ReadLine()
End While

ReadToEnd doesn't read line by line, instead it reads the entire content of the stream...

Upvotes: 1

Related Questions