Binary Reader and Writer open at same time?

…衆ロ難τιáo~ 提交于 2019-12-05 16:54:46

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:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!