Eggord Eggord - 1 year ago 103 Question

Simultaneously read and write binary file

I want to write and read a binary file simultaneously, but whenever I try to do so I always get an exception stating that the file is already in use by a different process. I know how to do it with a normal

but with a
it doesn't work.

Does anybody have an idea how to read and write a binary file simultaneously?

What I've done so far:

FileSt = New FileStream("file.bin", FileMode.Create,FileAccess.ReadWrite)
writer = New BinaryWriter(FileSt, enc)
reader = New BinaryReader(File.Open("file.bin", FileMode.Open))

Answer Source

You're opening the file twice - once for reading and once for writing. That means that one FileStream needs FileAccess.Read and FileShare.Write while the other needs FileAccess.Write and FileShare.Read. This code is tested and verified with a file that had already had an Integer and a String written to it with a BinaryWriter:

Dim filePath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Test.bin")

Using source = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Write),
      destination = File.Open(filePath, FileMode.Open, FileAccess.Write, FileShare.Read),
      reader As New BinaryReader(source),
      writer As New BinaryWriter(destination)
    Dim n = reader.ReadInt32()

    writer.Write("What's up doc?")

    Dim sz = reader.ReadString()
End Using

Note that you should only specify Read or Write if that's all that's needed. Only specify ReadWrite if you know that you will or might need both. The FileAccess value is for what this FileStream will do or may do to the file while the FileShare value is for what other FileStream objects opened on the same file are allowed to do.