0

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!")
Robert
  • 117
  • 10
  • Possible duplicate of [How to both read and write a file in C#](http://stackoverflow.com/questions/605685/how-to-both-read-and-write-a-file-in-c-sharp) – Alex B. Nov 02 '16 at 08:39
  • 1
    If your files are not that large, consider using [`File.ReadAllLines`](https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx) and [`File.WriteAllLines`](https://msdn.microsoft.com/en-us/library/system.io.file.writealllines(v=vs.110).aspx). – Zev Spitz Nov 02 '16 at 08:42
  • I'm looking into the FileStream command. Kinda figure it out how it works. Also opened to other possibilities. – Robert Nov 02 '16 at 08:51
  • @ZevSpitz Thanks, I already know that, but I am curious how can you do this for larges files "just in case". – Robert Nov 02 '16 at 08:52

1 Answers1

0

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.

Community
  • 1
  • 1
Zev Spitz
  • 10,414
  • 4
  • 49
  • 114