Ernesto
Ernesto

Reputation: 35

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?

Upvotes: 0

Views: 60

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54487

The point of ReadLines is to read the lines one by one, so that you can process them one by one and reduce the amount of memory used, rather than loading the entire file first and then processing the lines. You haven't shown us all the relevant code so it's hard to know which is more appropriate. If you want to read and filter the existing data, then write that filtered data and some new data back to the file then you can do that with ReadLines, but you have to do it properly, e.g.

'Read the file and keep only lines that start with the specified prefix.
Dim lines = File.ReadLines(filePath).
                 Where(Function(line) line.StartsWith(prefix)).
                 ToList()

'Add a new line to be written.
lines.Add(newLine)

'Overwrite the current file contents with the combined filtered and new data.
File.WriteAllLines(filePath, lines)

However you do it, you need to enumerate the result of ReadLines first and then the file will be closed, so you can open it again to write to it. As I said, this may or may not be preferable to using ReadAllLines, depending on information that you have not provided.

Upvotes: 1

Ry-
Ry-

Reputation: 225281

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.

Upvotes: 0

Related Questions