-1

This is a real head scratcher. According to all documentation, file.readAllLines should close the file it's reading from after it completes. But in my app, when I try to write to the file, it throws an IO exception saying "process cannot access the file because it is being used by another process". And this should be really simple - the file in question is only referenced twice - once when it's read into the app on first start, and then when you overwrite it. Here's the code:

Firstly, the code that opens the file (filepath used is c:\Test\cfg.fcs):

Public Function ReadALine(ByVal File_Path As String, ByVal TotalLine As Integer, ByVal Line2Read As Integer) As String
    Dim Buffer As Array
    Dim Line As String
    If TotalLine <= Line2Read Then
        Return "No Such Line"
    End If
    Buffer = File.ReadAllLines(File_Path)
    Line = Buffer(Line2Read)

    Return Line
End Function

It works perfectly, and should leave the file properly closed, right? but when I run the following a bit later in another module:

file = My.Computer.FileSystem.OpenTextFileWriter("c:\Test\cfg.fcs", False)
file.WriteLine(Form1.GlobalVariables.serialNumber)

it throws an exception saying the file's still in use. Those are the only two times in the whole app that file is even mentioned.

GSerg
  • 76,472
  • 17
  • 159
  • 346
Rocks
  • 107
  • 2
  • 12

1 Answers1

0

for anyone else running into this problem the solution was simple but still counterintuitive... the problem was only the sequence of the commands. I moved the file.writeline down to the bottom of the suband for some reason that fixed it. strange

Rocks
  • 107
  • 2
  • 12
  • 1
    Then it's a timing issue, most likely caused by [another part of your program you are not aware of](https://stackoverflow.com/a/31966611/11683) or e.g. [an antivirus](https://stackoverflow.com/questions/31950107/file-readalllines-quickly-followed-by-file-writealllines-causes-exception-du#comment51809843_31950107). – GSerg Oct 15 '17 at 11:57