开发者

Best way to get underlying data from MemoryStream?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜