c# - 使用自定义 Read() 和 Write() 功能装饰 FileStream

标签 c# stream decorator filestream

我正在尝试装饰 StreamCaesarStream类,基本上将凯撒密码应用于 ReadWrite运营。我已经设法覆盖 Write方法很容易,但是 Read让我头疼。据我了解,我需要调用底层 FileStreamRead方法并以某种方式修改它,但是如何让它读取值,同时向每个字节添加一个数字,类似于我在 Write() 中所做的方法?这对我来说更难,因为Read的返回值只是读取的字节数,而不是实际读取的项。

public class CaesarStream : Stream
{
    private int _offset;
    private FileStream _stream;

    public CaesarStream(FileStream stream, int offset)
    {
        _offset = offset;
        _stream = stream;
    }
    public override int Read(byte[] array, int offset, int count)
    {
        //I imagine i need to call 
        //_stream.Read(array, offset, count);
        //and modify the array, but how do i make my stream return it afterwards?
        //I have no access to the underlying private FileStream fields so I'm clueless
    }
    public override void Write(byte[] buffer, int offset, int count)
    {
        byte[] changedBytes = new byte[buffer.Length];

        int index = 0;
        foreach (byte b in buffer)
        {
            changedBytes[index] = (byte) (b + (byte) _offset);
            index++;
        }

        _stream.Write(changedBytes, offset, count);
    }
}

PS 我知道我还应该检查读/写的字节数并继续读/写直到完成,但我还没有做到这一点。我想先完成阅读部分。

最佳答案

按照尤金的建议,我设法让它按预期工作,下面是代码,以防有人想看它:

public class CaesarStream : Stream
{
    private int _offset;
    private FileStream _stream;


    public CaesarStream(FileStream stream, int offset)
    {
        _offset = offset;
        _stream = stream;
    }

    public override int Read(byte[] array, int offset, int count)
    {
        int retValue = _stream.Read(array, offset, count);

        for (int a = 0; a < array.Length; a++)
        {
            array[a] = (byte) (array[a] - (byte) _offset);
        }

        return retValue;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        byte[] changedBytes = new byte[buffer.Length];

        int index = 0;
        foreach (byte b in buffer)
        {
            changedBytes[index] = (byte) (b + (byte) _offset);
            index++;
        }

        _stream.Write(changedBytes, offset, count);
    }
}

关于c# - 使用自定义 Read() 和 Write() 功能装饰 FileStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36669138/

相关文章:

c# - 将 csv 内容发布到 HTTP API C#

c# - 在特定条件下跳过 specflow 规范

c# - 我的流不断抛出读/写超时异常

Python3有条件地装饰?

python - Redis 获取和设置装饰器

c# - GridView ASP.NET C# 中的丑陋时间格式

c# - 为什么我的 FlowDocument 不使用整个宽度?

c# - 将字节数组保存到文件

c++ - 如何通过缓冲区大小来优化读写?

python - 类定义中的自引用