Robert  Kodra Robert Kodra - 1 month ago 7
Vb.net Question

Search text file for a ranged value

I want to read and write the same file with StreamReader and StreamWriter. I know that in my code I am trying to open the file twice and that is the problem. Could anyone give me another way to do this? I got confused a bit.

As for the program, I wanted to create a program where I create a text if it doesnt exist. If it exists then it compares each line with a Listbox and see if the value from the Listbox appears there. If it doesnt then it will add to the text.

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!")

Answer

If your file is not that large, consider using File.ReadAllLines and File.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)

If the file is large, but you only have to write a few lines, then you can use 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)

If there are a large number of lines to write, then use the answers from this question.