Accessing base memorystream [for read] in a binarywriter

592 views Asked by At

I have a binarywriter that is backed by a memorystream as such:

BinaryWriter m_binaryWriter = new BinaryWriter(new MemoryStream(BUFFER_SIZE));

I want to get the base reader and read it into a byte array:

long DataLength = m_binaryWriter.BaseStream.Length;
byte[] MemoryStrData = new byte[DataLength];
int BytesRead = m_binaryWriter.BaseStream.Read(MemoryStrData, 0, (int)DataLength);

However, BytesRead is always 0 (and obviously MemoryStrData contains all 0's) . I have tried to use a BinaryReader to read the stream out of the base stream, but that resulted in the same thing. Am I missing something here?

2

There are 2 answers

4
Todd Bowles On

Do you always know that the BinaryWriter will be backed by a MemoryStream?

If so, either keep a reference to the MemoryStream around, or cast the BaseStream as appropriate, and then use MemoryStream.ToArray() to get a byte array of the contents of the MemoryStream.

0
bge0 On

I solved it. The BinaryWriter's current index seems to be different than it's backend stream's location! I figured that getting a handle to the basestream and then doing a .read(OutputArray,Index,Count) would be sufficient, but you need to do a seek on the BinaryWriter itself:

m_binaryWriter.Seek(0, SeekOrigin.Begin);