Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 373
Jyina Avatar asked Mar 14 '17 19:03

Jyina


1 Answers

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.

like image 153
Snicker Avatar answered Sep 22 '22 16:09

Snicker