从文本文件中读取和写入特定行

时间:2011-08-05 03:12:58

标签: .net vb.net streamreader streamwriter

我遇到Niphoet在Stack Overflow问题 Overwrite a specific line in a text file using VB.NET 中遇到的问题。

我正在尝试实现Axarydax在C#中显示的代码,我试图将其转换为用于VB.NET。我的问题是代码将生成我的新文本文件,但它不会将其他文本文件中的任何行写入它,只是将其留空。我认为我的问题是while循环语句,但我不确定。以下是我到目前为止的情况:

 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

1 个答案:

答案 0 :(得分:1)

如果您想逐行阅读文本文件,请将代码更改为:

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不会逐行读取,而是读取流的整个内容...