コード例 #1
0
ファイル: StreamUtils.cs プロジェクト: isaveu/common
        /// <summary>
        /// Writes the entire content of a stream to a file.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="path">The path of the file to write.</param>
        /// <param name="bufferSize">The size of the buffer to use for copying in bytes.</param>
        /// <param name="cancellationToken">Used to signal when the user wishes to cancel the copy process.</param>
        /// <param name="progress">Used to report back the number of bytes that have been copied so far. Callbacks are rate limited to once every 250ms.</param>
        public static void CopyToFile([NotNull] this Stream stream, [NotNull, Localizable(false)] string path, int bufferSize = 4096, CancellationToken cancellationToken = default, Tasks.IProgress <long> progress = null)
        {
            #region Sanity checks
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            #endregion

            using (var fileStream = File.Create(path))
                stream.CopyToEx(fileStream, bufferSize, cancellationToken, progress);
        }
コード例 #2
0
ファイル: StreamUtils.cs プロジェクト: isaveu/common
        public static void CopyToEx([NotNull] this Stream source, [NotNull] Stream destination, int bufferSize = 4096, CancellationToken cancellationToken = default, Tasks.IProgress <long> progress = null)
        {
            #region Sanity checks
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }
            #endregion

            if (source.CanSeek)
            {
                source.Position = 0;
            }

            var  buffer = new byte[bufferSize];
            int  read;
            long sum = 0;
            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                sum += read = source.Read(buffer, 0, buffer.Length);
                destination.Write(buffer, 0, read);
                progress?.Report(sum);
            } while (read != 0);
        }