EnumerableToStream Nuget package
Converts an IEnumerable<string>
to a Stream
:
using EnumerableToStream;
IEnumerable<string> enumerable = new [] {"Hello, ", "world!"};
Stream stream = enumerable.ToStream();
- The enumerable is evaluated lazily as the stream is read.
- The enumerable is properly disposed of when the stream is closed.
- ToStream() does zero allocations on .NET Standard 2.1 compatible runtimes.
- ToStream() supports encodings:
enumerable.ToStream(Encoding.UTF8);
- ToStream() accepts both
IEnumerable
andIAsyncEnumerable
. If you use the async version, you will need to callstream.ReadAsync()
rather thanRead()
.
Streaming query results to the client in a memory efficient manner:
public IActionResult Get()
{
IEnumerable<string> lines = GetLines();
Stream stream = lines.AddLineEndings().ToStream();
return File(stream, "text/csv");
}