【问题标题】:Search text file for a ranged value在文本文件中搜索范围值
【发布时间】:2016-11-02 08:31:44
【问题描述】:

我想用 StreamReader 和 StreamWriter 读写同一个文件。我知道在我的代码中我试图打开文件两次,这就是问题所在。谁能给我另一种方法来做到这一点?我有点糊涂了。

至于程序,我想创建一个程序,如果它不存在,我会在其中创建一个文本。如果它存在,那么它将每一行与一个列表框进行比较,并查看列表框中的值是否出现在那里。如果没有,那么它将添加到文本中。

    Dim SR As System.IO.StreamReader
    Dim SW As System.IO.StreamWriter


    SR = New System.IO.StreamReader("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
    SW = New System.IO.StreamWriter("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)

    Dim strLine As String


    Do While SR.Peek <> -1
        strLine = SR.ReadLine()
        For i = 0 To Cerberus.ListBox2.Items.Count - 1
            If Cerberus.ListBox2.Items.Item(i).Contains(strLine) = False Then
                SW.WriteLine(Cerberus.ListBox2.Items.Item(i))
            End If
        Next
    Loop

    SR.Close()
    SW.Close()
    SR.Dispose()
    SW.Dispose()
    MsgBox("Duplicates Removed!")

【问题讨论】:

标签: vb.net


【解决方案1】:

如果您的文件不是那么大,请考虑使用File.ReadAllLinesFile.WriteAllLines

Dim path = "D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt"

Dim lines = File.ReadAllLines(path) 'String() -- holds all the lines in memory
Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines)
File.AppendAllLines(path, linesToWrite)

如果文件很大,但你只需要写几行,那么你可以使用File.ReadLines

Dim lines = File.ReadLines(path) 'IEnumerable(Of String)\
    'holds only a single line in memory at a time
    'but the file remains open until the iteration is finished

Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines).ToList
File.AppendAllLines(path, linesToWrite)

如果要写的行数很多,请使用this question的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 2015-10-18
    • 2019-04-09
    • 2015-01-12
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多