Reputation: 13
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 FileStream
but with a BinaryReader
and BinaryWriter
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))
Upvotes: 0
Views: 1856
Reputation: 54417
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(98765)
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.
Upvotes: 0
Reputation: 13
You need to set the FileShare mode on the file.
FileStream blah = new FileStream("file.bin", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
Upvotes: 0
Reputation: 64933
You need to use the FileStream
constructor overload that can provide FileShare
mode.
See what MSDN states about FileShare.ReadWrite
mode:
Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
Upvotes: 2