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();
        }
    }
}
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot