开发者

Best way to get underlying data from MemoryStream?

开发者 https://www.devze.com 2023-04-01 14:54 出处:网络
The bytes are written to MemoryStream object and there is a need to get underlying buff开发者_如何学运维er to save it to file

The bytes are written to MemoryStream object and there is a need to get underlying buff开发者_如何学运维er to save it to file

MemoryStream ms = new MemoryStream();
// ms.Write(...)
// ms.Write(...)
// etc... some bytes are written to the stream

byte[] data = ms.GetBuffer();
int length = data.Length;

However the returned data is of ms capacity rather than the real ms length.

Is it better (faster, safer, ...) to set ms capacity to its length or allocate a data and copy ms contents into it?


just use the member-method ms.ToArray()


GetBuffer() was designed to avoid the potentially expensive array allocation. You can use the ToArray() method is you want a byte[] that's of the right size.


When you don't seek around to random places, you can also use the stream position:

Debug.Log("All length: " + (int)ms.Position);
0

精彩评论

暂无评论...
验证码 换一张
取 消