vb.netstreamwriterreadlines

need to close after FILE.READLINES


I need to read all content of a file but keep only some of the content and append new content. So I tried to use READLINES filter the lines I need to keep then rewrite the file with the kept lines and new ones:

Dim paramLines As IEnumerable
paramLines = File.ReadLines(Path & "X.ini")
Dim paramFile As StreamWriter = New StreamWriter(Path & "X.ini",append:=False)  
For Each paramline In paramLines
    if condition_iskeepIt then paramFile.WriteLine(paramline)
Next  ' paramLine

    ...write revised lines

However, this gives an error on the third line: System.IO.IOException: 'The process cannot access the file '...\X.ini' because it is being used by another process.'

What is holding the "process"? How do we get it to release?


Solution

  • File.ReadLines loads the file lazily. To load the lines of the file fully into memory, you can use File.ReadAllLines:

    Dim paramLines As String() = File.ReadAllLines(Path & "X.ini")
    Using paramFile As New StreamWriter(Path & "X.ini", append:=False)
        ' …
    End Using
    

    It is important to note that ReadAllLines loads all the file data in memory and thus (if the file is big) you will see a surge in the memory used by your application and a noticeable delay while the file is loaded.