Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
StreamWrapper.cs
2{
3 public sealed class StreamWrapper(Stream Wrapped, IDisposable? AdditionalDisposable) : Stream
4 {
5 private readonly Stream wrapped = Wrapped;
6 private IDisposable? additionalDisposable = AdditionalDisposable;
7
8 public event EventHandler? Disposed;
9
10 public StreamWrapper(Stream Wrapped) : this(Wrapped, null)
11 {
12 }
13
14 public override long Position
15 {
16 get => this.wrapped.Position;
17 set => this.wrapped.Position = value;
18 }
19
20 public override long Length => this.wrapped.Length;
21 public override bool CanRead => this.wrapped.CanRead;
22 public override bool CanSeek => this.wrapped.CanSeek;
23 public override bool CanWrite => this.wrapped.CanWrite;
24
25 public override void Flush() => this.wrapped.Flush();
26 public override int Read(byte[] Buffer, int Offset, int Count) => this.wrapped.Read(Buffer, Offset, Count);
27 public override long Seek(long Offset, SeekOrigin Origin) => this.wrapped.Seek(Offset, Origin);
28 public override void SetLength(long Value) => this.wrapped.SetLength(Value);
29 public override void Write(byte[] Buffer, int Offset, int Count) => this.wrapped.Write(Buffer, Offset, Count);
30
31 protected override void Dispose(bool Disposing)
32 {
33 this.wrapped.Dispose();
34
35 Disposed?.Invoke(this, EventArgs.Empty);
36
37 this.additionalDisposable?.Dispose();
38 this.additionalDisposable = null;
39
40 base.Dispose(Disposing);
41 }
42
43 public static async Task<Stream?> GetStreamAsync(Uri uri, HttpClient client, CancellationToken cancellationToken)
44 {
45 HttpResponseMessage response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false);
46
47 if (!response.IsSuccessStatusCode)
48 {
49 return null;
50 }
51
52 // it needs to be disposed after the calling code is done with the stream
53 // otherwise the stream may get disposed before the caller can use it
54 return new StreamWrapper(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), response);
55 }
56 }
57}