Feb 19
It’s fairly easy to convert a C# String to a Stream and vice-versa.
Convert String to Stream
To convert a C# String to a MemoryStream object, use the GetBytes Encoding method to create a byte array, then pass that to the MemoryStream constructor:
byte[] byteArray = Encoding.ASCII.GetBytes( test ); MemoryStream stream = new MemoryStream( byteArray );
Convert Stream to String
To convert a Stream object (or any of its derived streams) to a C# String, create a StreamReader object, then call the ReadToEnd method:
StreamReader reader = new StreamReader( stream ); string text = reader.ReadToEnd();
Console Test Program
Here is a simple test program to demonstrate this round-trip conversion:
using System;
using System.IO;
using System.Text;
namespace CSharp411
{
class Program
{
static void Main( string[] args )
{
string test = "Testing 1-2-3";
// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes( test );
MemoryStream stream = new MemoryStream( byteArray );
// convert stream to string
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
Console.WriteLine( text );
Console.ReadLine();
}
}
}
Popularity: 72% [?]
Related posts:

How about using a StreamWriter instead of Encoding? That would really mirror your use of StreamReader, and it would be more efficient when not working with in-memory streams.
just what I needed…thx
)
Yes, you can also use StreamWriter, which as you say provides more symmetry, though also more code. You need to call Flush() to complete the write, and you also need to reset the Stream position to zero when starting the read. Here is the modified code:
string test = "Testing 1-2-3″;
// convert string to stream
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter( stream );
writer.Write( test );
writer.Flush();
// convert stream to string
stream.Position = 0;
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
Thanks,
There is a little more code when using the memory stream however it does not require you to know the encoding whereas using GetBytes requires you to know the encoding ahead of time
@AndrewSeven Using a MemoryStream and StreamWriter doesn't get around choosing an encoding. You have to have an encoding to express a string in bytes.
The StreamWriter constructor uses the "the default encoding and buffer size" if they are not specified (see http://msdn.microsoft.com/en-us/library/aa328965%28VS.71%29.aspx).
By using a MemoryStream and StreamWriter you aren't avoiding choosing an encoding, just making it implicit rather than explicit.