예제 #1
0
        internal static IAsyncOperationWithProgress <IBuffer, uint> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, uint count)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream is MemoryStream);
            Debug.Assert(stream.CanRead);
            Debug.Assert(stream.CanSeek);
            Debug.Assert(buffer != null);
            Debug.Assert(0 <= count);
            Debug.Assert(count <= int.MaxValue);
            Debug.Assert(count <= buffer.Capacity);

            // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
            // This is permitted by the WinRT stream contract.
            // The user specified buffer will not have any data put into it:
            buffer.Length = 0;

            MemoryStream memStream = stream as MemoryStream;

            Debug.Assert(memStream != null);

            try
            {
                IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((int)memStream.Position, (int)count);
                if (dataBuffer.Length > 0)
                {
                    memStream.Seek(dataBuffer.Length, SeekOrigin.Current);
                }

                return(AsyncInfo.CreateCompletedOperation <IBuffer, uint>(dataBuffer));
            }
            catch (Exception ex)
            {
                return(AsyncInfo.CreateFaultedOperation <IBuffer, uint>(ex));
            }
        }  // ReadAsync_MemoryStream