gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:27:02 24 4
gpt4 key购买 nike

我正在尝试用 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 我知道我还应该检查读/写的字节数并继续读/写直到完成,但我还没有做到这一点。我想先完成阅读部分。

最佳答案

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com