二进制读取器和写入器同时打开?
我正在编写处理使用哈希的文件的代码。我需要读取一个块,然后对其进行哈希处理,然后写入它,然后读取另一个块,等等。
换句话说,我需要进行大量的读取和写入。我确信这真的很简单,但我只是想由专业人士运行它...
是否可能并且可以接受做类似的事情:
BinaryReader br = new BinaryReader (File.OpenRead(path));
BinaryWriter bw = new BinaryWriter (File.OpenWrite(path));
br.dostuff();
bw.dostuff();
我记得在尝试打开和写入时遇到某种冲突的文件流错误文件,我不确定我做了什么来获取它。问题是两个文件流吗?我可以有一个流来读取和写入吗?
I'm writing code that deals with a file that uses hashes. I need to read a chunk, then hash it, then write it, then read another chunk, etc.
In other words, I need to do a lot of reading and writing. I'm sure this is really simple, but I just wanted to run it by the pros...
Is it possible, and acceptable to do something like:
BinaryReader br = new BinaryReader (File.OpenRead(path));
BinaryWriter bw = new BinaryWriter (File.OpenWrite(path));
br.dostuff();
bw.dostuff();
I remember running into some sort of conflicting file streams error when experimenting with opening and writing to files, and I'm not sure what I had done to get it. Is it two file streams that's the issue? Can I have one stream to read from and write to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是完全可能和期望的,从技术上讲,如果您的写入方法不会改变文件的长度并且始终落后于读取器,那么这应该不会产生任何问题。事实上,从 API 的角度来看,这是可取的,因为这允许用户控制从哪里读取和向哪里写入。 (建议写入不同的文件,以防在加密过程中发生任何不好的事情,您的输入文件不会被弄乱)。
就像:
现在由于您正在使用加密,我什至建议在另一个专用流中执行实际加密。这很好地清理了代码。
This is perfecty possible and desired, A technicality, if your write method doesn't change the length of the file and is always behind the reader, this should not give any problems. In fact, from an API point of view, this is desirable since this allows the user to control where to read from and where to write to. (It's a recommended specification to write to a different file, in case any bad things happen during the encryption process, your input file wont be messed up).
Something like:
Now since you're using an encryption, i would even recommend to perform the actual encryption in another specialized stream. This cleans the code up nicely.