二进制Reader和Writer在同一时间打开? [英] Binary Reader and Writer open at same time?

查看:288
本文介绍了二进制Reader和Writer在同一时间打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写代码,与使用哈希文件交易。我需要读一大块,那么散列它,然后写出来,然后读取另一个块等。

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?

推荐答案

这是perfecty可能和需要,学术性,如果你写方法并没有改变的文件的长度,并始终读者后面,这不应该给任何问题。事实上,从一个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).

喜欢的东西:

protected void Encrypt(Stream input, Stream output)
{
    byte[] buffer = new byte[2048];

    while (true)
    {
        // read 
        int current = input.Read(buffer, 0, buffer.Length);
    if (current == 0)
                     break;

        // encrypt
        PerformActualEncryption(buffer, 0, current);

        // write
        output.Write(buffer, 0, current);
    }   
}

public void Main()
{
    using (Stream inputStream  = File.Open("file.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (Stream outputStream = File.Open("file.dat", FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
    {
        Encrypt(inputStream, outputStream);
    }
}

现在,因为你使用的是加密的,我会甚至建议在另一个专门的流执行实际的加密。这清除代码了很好

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.

class MySpecialHashingStream : Stream
{
...
}

protected void Encrypt(Stream input, Stream output)
{
    Stream encryptedOutput = new MySpecialHashingStream(output);
    input.CopyTo(encryptedOutput);
}

这篇关于二进制Reader和Writer在同一时间打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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