Skip to content

soenneker/soenneker.utils.memorystream

Repository files navigation

Soenneker.Utils.MemoryStream

An easy modern MemoryStream utility

A library for management and simple access of RecyclableMemoryStreamManager

Installation

dotnet add package Soenneker.Utils.MemoryStream

Usage

  1. Register the interop within DI (Program.cs).
public static async Task Main(string[] args)
{
    ...
    builder.Services.AddMemoryStreamUtil();
}
  1. Inject IMemoryStreamUtil wherever you need MemoryStream services

  2. Retrieve a fresh MemoryStream from

Example:

public class TestClass{

    IMemoryStreamUtil _memoryStreamUtil;

    public TestClass(IMemoryStreamUtil memoryStreamUtil)
    {
        _memoryStreamUtil = memoryStreamUtil;
    }

    public async ValueTask<MemoryStream> ReadFileIntoMemoryStream(string path)
    {
        MemoryStream memoryStream = await _memoryStreamUtil.Get(); // .GetSync() is also available

        FileStream fileStream = File.OpenRead(path);

        await fileStream.CopyToAsync(memoryStream);
    
        return memoryStream;
    }
}