VB使用其他文本文件中的数据覆盖文本文件

时间:2015-01-06 19:04:34

标签: vb.net streamreader

所以我有两个文本文件showInfo,其中包含有关戏剧的信息。

当程序运行时,我选择一个月(例如,9月,11月),程序打开showInfo.txt并逐行查看所选月份。如果它检查的行与所选月份不匹配,则该文本将保存到temp.txt。找到后,它会加载接下来的两行,其中包含我可以编辑/更新的标题和说明,然后单击“保存”。

那么我有两个文件,一个保存所有原始信息,另一个保存编辑信息以及导致所选月份的月份。我想知道是否有办法将这两者结合起来并保留更新的信息?

Try
    Dim tempFile As StreamWriter = New StreamWriter("..\..\resources\temp.txt")
    Dim showFile As StreamReader = New StreamReader("..\..\resources\showInfo.txt")
    Do
        With showFile
            Dim month As String = showFile.ReadLine, title As String = showFile.ReadLine, des As String = showFile.ReadLine
            MsgBox("LOOKING FOR " & showTitle & " READ " & title & " FROM FILE.")
            If title = showTitle Then
                MsgBox("Found" & showTitle)
                found = True

                tempFile.WriteLine(cmbMonth.Text)
                tempFile.WriteLine(txtTitle.Text)
                tempFile.WriteLine(txtDescription.Text)

            Else
                tempFile.WriteLine(month)
                tempFile.WriteLine(title)
                tempFile.WriteLine(des)

            End If

            If found Then
                File.Copy("temp.txt", "ShowInfo.txt", True)
            End If

            'MsgBox("Are you sure you want to save this?.", MsgBoxStyle.YesNo, "Warning!")
            'tempFile.Close()
            'MsgBox("Your file has been successfully saved.", MsgBoxStyle.Information, "Successfully saved.")

        End With
    Loop Until found

    tempFile.Close()
    showFile.Close()

1 个答案:

答案 0 :(得分:0)

您可以在循环外移动复制操作。这样,一旦找到了您要查找的行并替换它们,您仍然会将其余数据复制到temp.txt。将代码修改为以下内容。请原谅我可能被屠杀的基础......已经有一段时间了:

While Not ShowFile.EndOfStream
    Dim month As String = showFile.ReadLine
    Dim title As String = showFile.ReadLine
    Dim des As String = showFile.ReadLine
    MsgBox("LOOKING FOR " & showTitle & " READ " & title & " FROM FILE.")
    If title = showTitle Then
        MsgBox("Found" & showTitle)

        tempFile.WriteLine(cmbMonth.Text)
        tempFile.WriteLine(txtTitle.Text)
        tempFile.WriteLine(txtDescription.Text)
    Else
        tempFile.WriteLine(month)
        tempFile.WriteLine(title)
        tempFile.WriteLine(des)
    End If
End While
tempFile.Close()
showFileClose()

' now copy
File.Copy("temp.txt", "ShowInfo.txt", true)

这里存在的一个危险是,如果showTitle存在超过一个月,那么您将要更改所有这些地方。如果您不想这样做,请使用found标记并稍微更改您的代码:

    if (Not found) And (title = showTitle) Then
        MsgBox(...)
        found = True
        ...