Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to ReadOnlyMemory<byte> in C#?

Tags:

c#

.net

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.

like image 246
Tom Warner Avatar asked Apr 28 '26 18:04

Tom Warner


2 Answers

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;
    ...
}
like image 110
Panagiotis Kanavos Avatar answered May 01 '26 07:05

Panagiotis Kanavos


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));
like image 20
Tom Warner Avatar answered May 01 '26 06:05

Tom Warner