dotnet / dotNext

Next generation API for .NET
https://dotnet.github.io/dotNext/
MIT License
1.6k stars 119 forks source link

The CopyTo method not supported #72

Closed iigoshkin closed 3 years ago

iigoshkin commented 3 years ago

Hey! I use the PooledBufferWriter class from the DotNext v 3.2.1 package, after converting to Stream, then call the CopyTo method and get an exception NotSupportedException I wanted to know if it was so conceived or am I doing something wrong?

using var writer = new PooledBufferWriter<byte>(ArrayPool<byte>.Shared.ToAllocator());
using Stream writeStream = StreamSource.AsStream(writer);
using MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(new byte[1024]);

writeStream.CopyTo(memoryStream); // thow exception 
sakno commented 3 years ago

Hey @iigoshkin , that's the correct behavior. StreamSource.AsStream creates writable-only stream for the buffer writer. CopyTo requires that the stream must be readable. For the returned stream, CanRead property always returns false.

If you want to copy buffer from the writer to the stream then you can use the following code:

using var writer = new PooledBufferWriter<byte>(ArrayPool<byte>.Shared.ToAllocator());
using MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(writer.WrittenMemory.Span);

If you want to read buffer via Stream:

using var writer = new PooledBufferWriter<byte>(ArrayPool<byte>.Shared.ToAllocator());
using Stream reader = StreamSource.AsStream(writer.WrittenMemory);
iigoshkin commented 3 years ago

Thanks! I will use your solution