I would like to convert a String to a ReadOnlyMemory<byte> object. It's easy to convert a string to a ReadOnlyMemory<char> object (using .AsMemory()) but there's no direct way to convert that to type byte, or directly convert the string otherwise.
Thee is a way. The EncodingExtensions class contains GetBytes extension methods that can write to an IBuffeWriter< T>. Two built-in classes implement this interface, ArrayBufferWriter<> and PipeWriter.
In APIs that use System.IO.Pipelines it's better to write to a PipeWriter directly rather than create an intermediate object. I'll use ArrayBufferWriter instead, because ... it's easier. It still allows memory to be reused instead of allocating new buffers:
var text=".....";
var writer=new ArrayBufferWrite(8192);
Encoding.UTF8.GetBytes(text,writer);
var memory=writer.WrittenMemory;
WrittenMemoy returns a ReadOnlyMemory<T> object with the written data.
The buffer can be cleared with Reset() and reused :
var writer=new ArrayBufferWrite(8192);
while(true)
{
writer.Reset();
var text=SomehowGetString();
Encoding.UTF8.GetBytes(text,writer);
var memory=writer.WrittenMemory;
...
}
The most straightforward way I found is by converting the string to a byte[] and returning that as ReadOnlyMemory, like so:
var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With