【问题标题】:Decorating FileStream with custom Read() and Write() functionalities使用自定义 Read() 和 Write() 功能装饰 FileStream
【发布时间】:2016-04-16 20:07:03
【问题描述】:

我正在尝试用CaesarStream 类装饰Stream 类,它基本上将凯撒密码应用于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 我知道我还应该检查读/写的字节数并继续读/写直到它完成,但我还没有做到这一点。我想先完成阅读部分。

【问题讨论】:

  • 您只需以与Write 方法相同的方式(仅通过减少_offset)修改array。除了base.Read 的返回值,您不需要返回任何其他内容,因为array 是一个引用 - stackoverflow.com/questions/967402/…
  • @Eugene 为了确保我理解正确,我调用 FileStream 的 Read 并将一个移位零数组传递给它,它会读入它吗?
  • @Marchin 你用你收到的参数调用base.Read,然后你遍历数组中的每个元素(直到base.Read返回的计数)并就地解密它们。然后,调用者将在传递给您的array 中获得已经破译的数据。
  • 成功了,非常感谢。它实际上比我预期的要简单

标签: c# stream decorator filestream


【解决方案1】:

按照 Eugene 的建议,我设法使其按预期工作,以下是代码以防有人想查看:

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);
    }
}

【讨论】:

  • 这些方法应该考虑offset和count。按照他们的立场,他们修改了整个数组。
猜你喜欢
  • 2013-02-27
  • 2021-11-20
  • 2017-12-11
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2021-01-17
相关资源
最近更新 更多