Coder Perfect

What is the best way to create a stream from a string?


I need to develop a unit test for a method that accepts a stream from a text file as input. I’d like to do something similar like this:

Stream s = GenerateStreamFromString("a,b \n c,d");

Asked by Omu

Solution #1

public static Stream GenerateStreamFromString(string s)
    var stream = new MemoryStream();
    var writer = new StreamWriter(stream);
    stream.Position = 0;
    return stream;

Don’t forget to include the phrase “using” in your sentence.

using (var stream = GenerateStreamFromString("a,b \n c,d"))
    // ... Do stuff to stream

Concerning the StreamWriter’s non-disposal. StreamWriter is nothing more than a wrapper around the underlying stream; it doesn’t use any resources that need to be disposed of. The underlying Stream that StreamWriter is writing to will be closed by the Dispose function. That is the MemoryStream we wish to return in this scenario.

The underlying stream is kept open when the writer is disposed of in.NET 4.5 thanks to an overload for StreamWriter, but this code performs the same thing and works with older versions of.NET as well.

See Is it possible to shut off a StreamWriter without also shutting down its BaseStream?

Answered by Cameron MacFarland

Solution #2

Another solution:

public static MemoryStream GenerateStreamFromString(string value)
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));

Answered by joelnet

Solution #3

This should be added to a static string utility class:

public static Stream ToStream(this string str)
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    stream.Position = 0;
    return stream;

This adds an extension function, allowing you to do things like:

using (var stringStream = "My string".ToStream())
    // use stringStream

Answered by Josh G

Solution #4

public Stream GenerateStreamFromString(string s)
    return new MemoryStream(Encoding.UTF8.GetBytes(s));

Answered by Warlock

Solution #5

ToStream extension methods have been modernized and somewhat modified:

public static Stream ToStream(this string value) => ToStream(value, Encoding.UTF8);

public static Stream ToStream(this string value, Encoding encoding) 
                          => new MemoryStream(encoding.GetBytes(value ?? string.Empty));

@Palec’s reply on @Shaun Bowe’s answer recommended a change.

Or, as @satnhak suggested, as a one-liner:

public static Stream ToStream(this string value, Encoding encoding = null) 
    => new MemoryStream((encoding ?? Encoding.UTF8).GetBytes(value ?? string.Empty));

Answered by Nick N.

Post is based on