/// <summary>Reads the contents of the stream asynchronously.</summary>
        /// <param name="stream">The stream.</param>
        /// <returns>A Task representing the contents of the file in bytes.</returns>
        public static Task<byte[]> ReadAllBytesAsync(this Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            // Create a MemoryStream to store the data read from the input stream
            int initialCapacity = stream.CanSeek ? (int)stream.Length : 0;
            var readData = new MemoryStream(initialCapacity);

            // Copy from the source stream to the memory stream and return the copied data
            return stream.CopyStreamToStreamAsync(readData).ContinueWith(t =>
            {
                t.PropagateExceptions();
                return readData.ToArray();
            });
        }
Example #2
0
        /// <summary>
        /// <paramref name="stream"/>의 모든 Data를 비동기 방식으로 읽는 작업을 생성합니다.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Task<byte[]> ReadAllBytesAsync(this Stream stream) {
            if(IsDebugEnabled)
                log.Debug("스트림의 내용을 비동기 방식으로 모두 읽어 바이트 배열로 반환하는 Task<byte[]>를 빌드합니다.");

            var initialCapacity = stream.CanSeek ? (int)stream.Length : BufferSize;
            var destStream = new MemoryStream(initialCapacity);

            return
                stream
                    .CopyStreamToStreamAsync(destStream)
                    .ContinueWith(antecedent => {
                        var result = destStream.ToArray();
                        destStream.Close();

                        if(IsDebugEnabled)
                            log.Debug("원본 스트림의 내용을 비동기 방식으로 모두 읽어 byte 배열로 만들었습니다.");

                        return result;
                    },
                                  TaskContinuationOptions.ExecuteSynchronously);
        }
        /// <summary>
        /// Reads the contents of the stream asynchronously and converts it into <see cref="T:XDocument"/>.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>A Task representing <see cref="T:XDocument"/> object.</returns>
        public static Task<XDocument> ReadXmlAsync(this Stream stream)
        {
            Contract.Requires(stream != null);

            // Create a MemoryStream to store the data read from the input stream
            int initialCapacity = stream.CanSeek ? (int)stream.Length : 0;
            var readData = new MemoryStream(initialCapacity);

            // Copy from the source stream to the memory stream and return the copied data
            return stream.CopyStreamToStreamAsync(readData).ContinueWith(t =>
            {
                t.PropagateExceptions();
                readData.Position = 0;
                return XDocument.Load(readData);
            });
        }