如何从 IRandomAccessStream 获取 IBuffer

How to get an IBuffer from an IRandomAccessStream

如果我有一个 IRandomAccessStream 对象,我该如何创建一个 IBuffer 对象?

我发现最简单的方法是通过 MemoryStream.GetWindowsRuntimeBuffer :

IRandomAccessStream stream = ...;

using (var memoryStream = new MemoryStream())
{
    memoryStream.Capacity = (int)stream.Size;
    var ibuffer = memoryStream.GetWindowsRuntimeBuffer();
    await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None).AsTask().ConfigureAwait(false);
}