public static Task ReadAsFileStreamAsync(this HttpContent content, string path, bool overwrite = true) { if (!overwrite && File.Exists(path)) { throw new InvalidOperationException(string.Format("File {0} already exists!", path)); } FileStream fileStream = null; try { fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); return content.CopyToAsync(fileStream).ContinueWith( task => { fileStream.Close(); }); } catch (Exception e) { if (fileStream != null) { fileStream.Close(); } throw e; } }
/// <summary> /// Reserved for internal use. /// </summary> public static Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite) { string pathname = Path.GetFullPath(filename); if (!overwrite && File.Exists(filename)) { throw new InvalidOperationException(string.Format("File {0} already exists.", pathname)); } FileStream fileStream = null; try { fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None); return content.CopyToAsync(fileStream).ContinueWith(_ => fileStream.Close()); } catch { if (fileStream != null) { fileStream.Close(); } throw; } }
public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream) { Stream streamToConvert = null; if (!stream.CanRead) { throw new Exception("Cannot read the source stream-"); } if (!stream.CanSeek) { MemoryStream memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); streamToConvert = memoryStream; } else { streamToConvert = stream; } DataReader dataReader = new DataReader(streamToConvert.AsInputStream()); streamToConvert.Position = 0; await dataReader.LoadAsync((uint)streamToConvert.Length); IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length); InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0); await outputstream.WriteAsync(buffer); await outputstream.FlushAsync(); return randomAccessStream; }
public static Task<byte[]> ReadAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { if (stream == null) { throw new ArgumentNullException("stream"); } var temp = new MemoryStream(stream.CanSeek ? (int)stream.Length : 0); return stream.CopyToAsync(temp, null, cancellationToken) .Then(() => temp.ToArray()); }
public static async Task SaveAsAsync(this IFormFile uploadFile, string filePath) { using (var stream = System.IO.File.Create(filePath)) { await uploadFile.CopyToAsync(stream); } }
/// <summary> /// Copies the stream to a byte array. /// </summary> /// <param name="input">Stream to read from</param> /// <returns>Byte array copy of a stream</returns> public static async Task<byte[]> ReadBytesAsync(this Stream input) { using (MemoryStream ms = new MemoryStream()) { await input.CopyToAsync(ms); return ms.ToArray(); } }
/// <summary> /// Converts a stream to a data URL. /// </summary> /// <param name="stream">The stream which provides the content for the data URI.</param> /// <param name="mediaType">The media type of the stream.</param> /// <returns>A string that contains the data uri of the stream's content.</returns> public static async Task<string> ToDataUri(this Stream stream, string mediaType) { // copy to memory stream and convert the bytes to a base64 encoded string using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); return ms.ToArray().ToDataUri(mediaType); } }
/// <summary> /// Asynchronously writes the stream contents to a byte array. /// </summary> /// <param name="stream"> /// The stream to convert to byte array. /// </param> /// <returns> /// A byte array of the <paramref name="stream"/>'s content. /// </returns> public async static Task<byte[]> ToArrayAsync(this Stream stream) { using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); return memoryStream.ToArray(); } }
/// <summary> /// Saves a stream to a file. /// </summary> /// <param name="stream">The stream.</param> /// <param name="pathToFile">The path to file.</param> public static async Task SaveToFileAsync(this Stream stream, string pathToFile) { Check.NotNull(stream, nameof(stream)); Check.NotEmpty(pathToFile, nameof(pathToFile)); using (Stream output = File.Open(pathToFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { await stream.CopyToAsync(output).ConfigureAwait(false); } }
public async static Task ReadAsFileAsync(this HttpContent content, string fileName) { string pathName = Path.GetFullPath(fileName); using(FileStream fileStream = new FileStream(pathName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { await content.CopyToAsync(fileStream); } }
public static async Task<HttpResponseMessage> ToHttpResponseMessage(this Stream stream) { var response = new HttpResponseMessage(); var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); response.Content = new ByteArrayContent(memoryStream.ToArray()); response.Content.Headers.Add("Content-Type", "application/http;msgtype=response"); return await response.Content.ReadAsHttpResponseMessageAsync(); }
public static async Task<byte[]> GetBytesAsync(this Stream stream) { Requires.NotNull(stream, "stream"); using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); return memoryStream.ToArray(); } }
public static async Task<MemoryStream> CopyAsync(this Stream stream, CancellationToken cancellation) { MemoryStream buffer = new MemoryStream(); if (stream.CanSeek && stream.Position != 0) { stream.Seek(0, SeekOrigin.Begin); } await stream.CopyToAsync(buffer, 4096, cancellation); buffer.Seek(0, SeekOrigin.Begin); return buffer; }
public static async Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite) { string pathname = Path.GetFullPath(filename); if (!overwrite && File.Exists(filename)) { throw new InvalidOperationException(string.Format("File {0} already exists.", pathname)); } using (var fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None)) { await content.CopyToAsync(fileStream); fileStream.Close(); } }
/// <summary> /// Asynchronously reads the bytes from a source stream and writes them to a destination stream. /// </summary> /// <remarks> /// <para>Copying begins at the current position in <paramref name="stream"/>.</para> /// </remarks> /// <param name="stream">The source stream.</param> /// <param name="destination">The stream to which the contents of the source stream will be copied.</param> /// <returns>A task that represents the asynchronous copy operation.</returns> /// <exception cref="ArgumentNullException"> /// <para>If <paramref name="stream"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ObjectDisposedException"> /// <para>If <paramref name="stream"/> is disposed.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> is disposed.</para> /// </exception> /// <exception cref="NotSupportedException"> /// <para>If <paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> does not support writing.</para> /// </exception> public static Task CopyToAsync(this Stream stream, Stream destination) { #if NET45PLUS if (stream == null) throw new ArgumentNullException("stream"); // This code requires the `Stream` class provide an implementation of `CopyToAsync`. The unit tests will // detect any case where this results in a stack overflow. return stream.CopyToAsync(destination); #else return CopyToAsync(stream, destination, 16 * 1024, CancellationToken.None); #endif }
internal static async Task ReadAsFileAsync(this HttpContent content, string filename) { var pathname = Path.GetFullPath(filename); FileStream stream = null; try { stream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None); await content.CopyToAsync(stream); stream.Close(); } catch { if (stream != null) { stream.Close(); } File.Delete(filename); throw; } }
/// <summary> /// Asynchonously read the <paramref name="stream"/> as String using the given <paramref name="encoding"/>. /// </summary> /// <param name="stream">The stream to read</param> /// <param name="encoding">The default encoding to use</param> /// <param name="detectEncodingFromByteOrderMarks">Whether to look for byte order marks to detect encoding</param> /// <param name="ct">The cancellation token used to cancel this operation</param> /// <returns>The stream's content read as string</returns> public static async Task<string> ReadStringAsync(this Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, CancellationToken ct) { const int BUFFER_SIZE = 4096; if(stream == null) throw new ArgumentNullException("stream"); ct.ThrowIfCancellationRequested(); var ms = new MemoryStream(); await stream.CopyToAsync(ms, BUFFER_SIZE, ct); ms.Position = 0; ct.ThrowIfCancellationRequested(); // Read stream data using(var readStream = new StreamReader(ms, Encoding.UTF8, detectEncodingFromByteOrderMarks, BUFFER_SIZE)) return await readStream.ReadToEndAsync(); // Todo: Cancellation support }
/// <summary> /// Copies the content of a <see cref="Stream"/> into a <see cref="IPipelineWriter"/>. /// </summary> /// <param name="stream"></param> /// <param name="writer"></param> /// <returns></returns> public static Task CopyToAsync(this Stream stream, IPipelineWriter writer) { return stream.CopyToAsync(new PipelineWriterStream(writer)); }
public static async Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken) => await stream.CopyToAsync(destination, DefaultCopyBufferSize, cancellationToken);
/// <summary> /// Reads the content from the stream as binary. /// </summary> /// <param name="stream">The stream.</param> /// <returns>byte array with the stream content.</returns> public static async Task<byte[]> ReadBinaryContentAsync(this Stream stream) { Check.NotNull(stream, nameof(stream)); MemoryStream memStream = stream as MemoryStream; if (memStream != null) { return memStream.ToArray(); } using (MemoryStream ms = new MemoryStream()) { await stream.CopyToAsync(ms).ConfigureAwait(false); return ms.ToArray(); } }
/// <summary> /// Saves a stream to another stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="outputStream">The output stream.</param> public static Task SaveToStreamAsync(this Stream stream, Stream outputStream) { Check.NotNull(stream, nameof(stream)); Check.NotNull(outputStream, nameof(outputStream)); return stream.CopyToAsync(outputStream); }
/// <summary> /// Asynchronously reads the bytes from a source stream and writes them to a destination stream, /// using a specified buffer size and cancellation token. /// </summary> /// <remarks> /// <para>If the operation is canceled before it completes, the returned task contains the <see cref="TaskStatus.Canceled"/> /// value for the <see cref="Task.Status"/> property.</para> /// <para> /// Copying begins at the current position in <paramref name="stream"/>. /// </para> /// </remarks> /// <param name="stream">The source stream.</param> /// <param name="destination">The stream to which the contents of the source stream will be copied.</param> /// <param name="bufferSize">The size, in bytes, of the buffer. This value must be greater than zero. The default size is 81920.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A task that represents the asynchronous copy operation.</returns> /// <exception cref="ArgumentNullException"> /// <para>If <paramref name="stream"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <para>If <paramref name="bufferSize"/> is negative or zero.</para> /// </exception> /// <exception cref="ObjectDisposedException"> /// <para>If <paramref name="stream"/> is disposed.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> is disposed.</para> /// </exception> /// <exception cref="NotSupportedException"> /// <para>If <paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para>If <paramref name="destination"/> does not support writing.</para> /// </exception> public static Task CopyToAsync(this Stream stream, Stream destination, int bufferSize, CancellationToken cancellationToken) { if (stream == null) throw new ArgumentNullException("stream"); if (destination == null) throw new ArgumentNullException("destination"); if (!stream.CanRead) throw new NotSupportedException("The stream does not support reading"); if (!destination.CanWrite) throw new NotSupportedException("The destination does not support writing"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); if (cancellationToken.IsCancellationRequested) return CompletedTask.Canceled(); #if NET45PLUS // This code requires the `Stream` class provide an implementation of `CopyToAsync`. The unit tests will // detect any case where this results in a stack overflow. return stream.CopyToAsync(destination, bufferSize, cancellationToken); #else return CopyToAsync(stream, destination, new byte[bufferSize], cancellationToken); #endif }
/// <summary> /// Writes the stream contents to a byte array. /// </summary> /// <param name="input">The input stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task<byte[]> ToArrayAsync(this Stream input) { #if PORTABLE await Task.FromResult(0); return null; #else var memoryStream = input as MemoryStream; if (memoryStream != null) { return memoryStream.ToArray(); } using (memoryStream = new MemoryStream()) { await input.CopyToAsync(memoryStream).ConfigureAwait(false); return memoryStream.ToArray(); } #endif }
public static async Task CopyToFileAsync(this Stream stream, string destinationFilePath) { #region Preconditions if (stream == null) throw new ArgumentNullException(nameof(stream)); if (destinationFilePath == null) throw new ArgumentNullException(nameof(destinationFilePath)); #endregion #region Ensure the directory exists var di = new DirectoryInfo(Path.GetDirectoryName(destinationFilePath)); if (!di.Exists) di.Create(); #endregion using (var writeStream = new FileStream(destinationFilePath, FileMode.CreateNew)) { await stream.CopyToAsync(writeStream).ConfigureAwait(false); } }
public static async Task CopyAndFlushAsync(this Stream source, Stream destination, IProgress<long> progress, CancellationToken cancellationToken) { await source.CopyToAsync(destination, progress, cancellationToken); await destination.FlushAsync(cancellationToken); }
/// <summary> /// Writes the stream contents to a byte array. /// </summary> /// <param name="input">The input stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task<byte[]> ToArrayAsync(this Stream input) { var memoryStream = input as MemoryStream; if (memoryStream != null) { return memoryStream.ToArray(); } using (memoryStream = new MemoryStream()) { await input.CopyToAsync(memoryStream).ConfigureAwait(false); return memoryStream.ToArray(); } }
/// <summary> /// Copies the given stream into another stream asynchronously. /// </summary> /// <param name="input">The given stream.</param> /// <param name="output">The stream that will be copied into.</param> /// <returns>An asynchronous task.</returns> public static Task CopyAsync(this Stream input, Stream output) { return input.CopyToAsync(output); }
public static async Task CopyToAsync(this Stream input, Stream output) { await input.CopyToAsync(output, short.MaxValue); return; }
public static async Task<byte[]> ReadToEndAsync(this Stream stream, long bufferSize = 1024 * 10) { var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); return memoryStream.ToArray(); }
/// <summary> /// Asynchronously reads the bytes from the current stream and writes them to a byte array, updating the specified progress and monitoring the specified cancellation token. /// </summary> /// <param name="source">The stream to be copied.</param> /// <param name="totalSize">The size, in bytes, of the current stream.</param> /// <param name="progress">The object to update when progress is made.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None"/></param> /// <returns>A task that represents the asynchronous copy operation. The value of the <code>TResult</code> parameter contains a reference to the <paramref name="destination"/>.</returns> public async static Task<byte[]> ToArrayAsync(this Stream source, long totalSize, IProgress<double> progress, double progressMin = 0.0, double progressMax = 100.0, CancellationToken cancellationToken = default(CancellationToken)) { bool canReportProgress = progress != null && totalSize > 0; byte[] result; var totalDone = 0L; if (totalSize > 0) { int bufferSize = GetOptimalBufferSize(totalSize); result = new byte[totalSize]; int read; while ((read = await source.ReadAsync(result, (int)totalDone, bufferSize, cancellationToken)) > 0) { cancellationToken.ThrowIfCancellationRequested(); if (canReportProgress) progress.Report(Math.Min(((double)totalDone) / ((double)totalSize) * (progressMax - progressMin) + progressMin, progressMax)); totalDone += read; } } else { using (MemoryStream memoryStream = new MemoryStream()) { await source.CopyToAsync(memoryStream, totalSize, progress, progressMin, progressMax, cancellationToken); result = memoryStream.ToArray(); } } if (totalDone != totalSize) progress.Report(progressMax); return result; }