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