Pages

Friday, November 25, 2011

C# Convert String to Stream, and Stream to String

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:
1
2
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:
1
2
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();

Console Test Program

Here is a simple test program to demonstrate this round-trip conversion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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();
        }
    }
}

No comments:

Post a Comment