Is it safe to get the allocated only bytes form a byte array obtained from GetBuffer?

StackOverflow https://stackoverflow.com/questions/8182909

  •  03-03-2021
  •  | 
  •  

Domanda

I have an instance of MemoryStream that is closed (don't ask, can't change that and it is not that poor design as it seems at first glance :). Anyway I found that I can take the byte[] using something like:

MemoryStream ms = SomeClass.GetMemoryStream();
byte[] myData = ms.GetBuffer();

Everything seems just great so far, the only problem I have is that the byte array returned from GetBuffer() is resized and contains unallocated space (byte)0; Like so:

12,32,43,43,2,3,0,0,0,0,0,0,0

My question is is it safe to assume that I can read the array until I encounter the first 0? Do you know any case in wich there will be (byte)0 in the middle of the data? The data is a MIME Email Message.

È stato utile?

Soluzione

Try ms.ToArray() : http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray.aspx

It works on a closed stream and returns a copy of the data, without the unused part of the buffer.

Altri suggerimenti

The msdn article on MemoryStream.GetBuffer Method says

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

Despite the copy it looks like what you are supposed to do...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top