Jyina
Jyina

Reputation: 2892

File.ReadAllBytes throws IOException saying the process can't access the file because it is being used by another process

Can File.ReadAllBytes cause IOException when it is called twice without enough interval between the calls?

When I set Row and Col of grid, it fires RowColChange event. The RowColChange has some code which opens the same file by using File.ReadAllBytes. I understand that ReadAllBytes internally uses using on FileStream so the filestream is closed after being used. But is it possible to have some delay in telling operating system that file is released so the subsequent usage of File.ReadAllBytes could fail and throw an exception. Any thoughts? Thank you!

grid.Row = 0
grid.Row = 1
grid.Col = 3


Private Sub grid_RowColChange(ByVal sender As Object, ByVal e As System.EventArgs) Handles grid.RowColChange
    'Is it possible to get IOException saying the process can't access the file because it is being used by another process.
     Display(File.ReadAllBytes(filePath))
End Sub

Upvotes: 7

Views: 11120

Answers (2)

Cee McSharpface
Cee McSharpface

Reputation: 8726

Building on this answer and the fact that File.ReadAllBytes uses the FileShare.Read flag in combination with FileAccess.Read (reference), concurrent calls to File.ReadAllBytes on the same file would never throw the "used by another process" IOException, unless another process already has it open with a write lock - FileShare.Read denies writing and would therefore fail.

If you see the exception because of concurrent writes, then yes, you have options:

  1. wait and retry. There is good coverage on this approach here on SO, for example this one

  2. Open a FileStream and specify FileShare.ReadWrite, as detailed here

Upvotes: 5

Snicker
Snicker

Reputation: 987

Please try the following:

Using fileStream = New FileStream("path", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    Using streamReader = New StreamReader(fileStream)
        Dim content = streamReader.ReadToEnd()
    End Using
End Using

It is actually possible that two threads read from the same file at the same file, please try to use the code above to read the file.

Upvotes: 5

Related Questions