12 April 2017

Generate a Stream from a String

in C#:
public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}

in VB:
Dim myStream As New MemoryStream(Encoding.UTF8.GetBytes(If(rawData, "")))



Another solution:
public static Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Don't forget to use Using:


using (Stream s = GenerateStreamFromString("a,b \n c,d"))
{
    // ... Do stuff to stream
}

About the StreamWriter not being disposed. StreamWriter is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The Dispose method will close the underlying Stream that StreamWriter is writing to. In this case that is the MemoryStream we want to return.

In .NET 4.5 there is now an overload for StreamWriter that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.



Trovato qui.