Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Stream that reports read progress
- /// </summary>
- public class ProgressStream : Stream
- {
- /// <summary>
- /// The progress will be reported in percent
- /// when reading from the stream;
- /// </summary>
- private IProgress<double> _readProgress;
- /// <summary>
- /// The actual stream that contains the desired data.
- /// </summary>
- private Stream _innerStream;
- private long _totalBytesRead = 0;
- private long _totalBytesWritten = 0;
- /// <summary>
- /// Creates a new instance of the <see cref="ProgressStream"/>
- /// </summary>
- /// <param name="innerStream">The actual stream that contains our data</param>
- /// <param name="readProgress">An implementation of <see cref="IProgress{T}"/>
- /// that will be used to get the progress of the read</param>
- /// <exception cref="ArgumentNullException">Thrown when innerStream or readProgress is null</exception>
- public ProgressStream(Stream innerStream, IProgress<double> readProgress)
- {
- _innerStream = innerStream ?? throw new ArgumentNullException(nameof(innerStream));
- _readProgress = readProgress ?? throw new ArgumentNullException(nameof(readProgress));
- }
- #region Overrides
- public override bool CanRead => _innerStream.CanRead;
- public override bool CanSeek => _innerStream.CanSeek;
- public override bool CanWrite => _innerStream.CanWrite;
- public override long Length => _innerStream.Length;
- public override long Position { get => _innerStream.Position; set => _innerStream.Position = value; }
- public override void Flush()
- => _innerStream.Flush();
- public override int Read(byte[] buffer, int offset, int count)
- {
- var read = _innerStream.Read(buffer, offset, count);
- _totalBytesRead += read;
- _readProgress.Report((_totalBytesRead / (double)_innerStream.Length) * 100F);
- return read;
- }
- public override long Seek(long offset, SeekOrigin origin)
- => _innerStream.Seek(offset, origin);
- public override void SetLength(long value)
- => _innerStream.SetLength(value);
- public override void Write(byte[] buffer, int offset, int count)
- => _innerStream.Write(buffer, offset, count);
- public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- => _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
- public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
- _totalBytesRead += read;
- _readProgress.Report((_totalBytesRead / (double)_innerStream.Length) * 100F);
- return read;
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- _innerStream.Dispose();
- }
- base.Dispose(disposing);
- }
- #endregion
- }
Add Comment
Please, Sign In to add comment