Home » CodeDigest


Convert String Variable to Stream and Stream to String Variable in C#
Submitted By Satheesh Babu B
On 6/27/2010 6:49:45 AM
Tags: C#,CodeDigest  

Convert String Variable to Stream and Stream to String Variable in C#


Sometimes, we may need to convert string variable to Stream object for further processing.


The System.IO namespace has a class called Encoding which can be used in these scenarios. You can convert a string into a byte array by calling the Encoding.ASCII.GetBytes() method.


With the byte[], you can obtain the Stream object by passing the byte array to the Stream class constructor.


Similarly, to obtain the string back from a Stream object you can call ReadToEnd() method of StreamReader class by passing the Stream object as a constrcutor argument.


This little code snippet will help us to convert a string variable to Stream object and back to String variable.


String to Stream
string str = "ASP.Net is great!";
byte[] bytes = Encoding.ASCII.GetBytes(str);
MemoryStream stream = new MemoryStream(bytes);


Stream object to string
StreamReader reader = new StreamReader(stream);
string str = reader.ReadToEnd();


You need to include System.IO namespace for the above code to work.


Happy coding!!


Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..