同时读写二进制文件 [英] Simultaneously read and write binary file

查看:134
本文介绍了同时读写二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时写入和读取二进制文件,但是每当尝试这样做时,我总是会收到一个异常,指出该文件已被其他进程使用.我知道如何使用普通的FileStream来执行此操作,但是使用BinaryReaderBinaryWriter时却行不通.

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?

到目前为止我所做的:

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

推荐答案

您要打开文件两次-一次用于读取,一次用于写入.这意味着一个FileStream需要FileAccess.ReadFileShare.Write,而另一个需要FileAccess.WriteFileShare.Read.使用已经使用BinaryWriter:

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

请注意,只需要指定ReadWrite即可.仅当您知道自己需要或可能同时需要两者时,才指定ReadWrite. FileAccess值表示此FileStream将对文件执行或可能执行的操作,而FileShare值表示允许在同一文件上打开的其他FileStream对象执行的操作.

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.

这篇关于同时读写二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆