BinaryReader
не настоящий _2 _... Это скорее наложение на другой поток. Вы могли:
using (var yourStream = /* ... */)
using (var br = new BinaryReader(yourStream))
{
using (var ms = new MemoryStream())
{
// Important the true, so that the ms remains open!
using (var bw = new BinaryWriter(ms, Encoding.UTF8, true))
{
var readed = br.ReadInt32();
bw.Write(readed);
// All the basic types are supported by various overlaods
}
// Here you have your ms... If you want to reread it:
ms.Position = 0;
using (var br2 = new BinaryReader(ms, Encoding.UTF8, true))
{
// Reread it
}
// Or copy it to another stream, or do whatever you want
}
}
Если вы просто хотите скопировать поток в другой поток во время его чтения, вы можете использовать что-то вроде:
public class CopyStream : Stream
{
// This is the stream you want to read your data from
public Stream ReadStream { get; set; }
// This is the "logger" stream, where a copy of read data will be put
public Stream LogStream { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
int res = ReadStream.Read(buffer, offset, count);
if (LogStream != null)
{
if (res > 0)
{
LogStream.Write(buffer, offset, res);
}
}
return res;
}
public override int ReadByte()
{
int res = ReadStream.ReadByte();
if (LogStream != null)
{
if (res >= 0)
{
LogStream.WriteByte((byte)res);
}
}
return res;
}
public override bool CanSeek
{
get { return false; }
}
}
Вам нужно будет реализовать / throw NotImplementedException()
многие другие методы, потому что Stream
- это abstract class
. Щелкните правой кнопкой мыши Stream
, Implement Abstract Class
ускорит это.
Основное использование:
var cs = new CopyStream
{
ReadStream = yourStream,
LogStream = whereyouwanttoWriteStream,
};
using (var br = new BinaryReader(CopyStream, Encoding.UTF8, true))
{
// Here you can read normally from the BinaryReader.
// Everything you read will be copied to LogStream
}
Обратите внимание, что создание подклассов BinaryReader
довольно сложно, потому что каждый метод загружает данные по-разному, поэтому нет единой «точки перехвата».
person
xanatos
schedule
22.03.2015
BinaryReader
над этим потоком, в то время как ваш собственный класс обернет внутренний поток в себя. Поэтому, когдаBinaryReader
вызываетRead
, он будет в вашем потоке, который будет выполнять чтение из базового потока и записывать прочитанные данные в другой поток во время той жеRead
операции. - person Luaan   schedule 23.03.2015