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(); } } }
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.
easy and helpful, thx)
hi …
I want to convert an array of string to a normal string variable…. can anyone give me the code….
eg :
string[] final should be converted to string fin….
@krishna: Use the Join method on the String class. For example, to join the array of strings with a newline between each string:
int count = 100;
string[] strings = new string[count]
for (int i = 0; i < count; i++) strings[i] = i.ToString(); string joined = String.Join( "n", strings );
Thanks it worked for me !
timm has just ripped this example from another author… just google it, to find the original one!
@timm: in future, please include a link to the original version to prevent copyright problems
@Peter: I can assure you this and all articles in C#411 are original. Can you provide a link to the article that you believe I copied?
@Peter: I just found my that code was indeed reproduced on CodeProject… a year after I wrote this article!
great contribution, just this need. Thank you very much
Whoa, thanks! This totally helped me this morning, and will hopefully save a group of technical writers from some horrible XAML documentation pain.
This is the response im getting from a server on my Windows Phone.
String ServerInfo = “~16 Johnnie Truemanv$£10 Jacki Coleman&%m”
v$£ are x,y,z coordinates respectively to be plotted on a map (z coordinate is irrelevant). They are meant to be Integers but the phone outputs them as these special characters. however that could be dealt with by using Convert.ToInt32(£), which i can do so that isnt a problem. But the main aim is to split them up into this form
into a new string array
in the form of
String [] someString = new String {(Name,x,y), (Name2,x1,y2)….}. Any help guys? Thanks.
This helps me,thx
memory stream from string to StreamReader
posted by timm was helpful for me
Thanks, really helped..!
These are useful suggestions. However, the reason that I want a stream for my string is to avoid duplicating the string. I’m dealing with potentially very large strings and don’t want to duplicate the content in a byte array or memory stream. In particular I am dealing with an interface implementation that returns a stream to be used to write to a SQL FILESTREAM field (for one interface consumer). The interface implementations don’t all produce a stream from a string, only some. I don’t want the large string copied in an intermediate form when transported from the string to the SqlFileStream instance. StringReader would have been perfect if it had derived from StreamReader (assuming it didn’t intrnally copy the string contents). The only thing I can think of is to write my own StringStreamReader class that derives from StreamReader. Any ideas?
Hi All,
i am converting string to stream like this:
StreamReader Code = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(refernceCode)));
As my refernceCode is having some special character, it is not encoding properly. I am getting ‘?’ in code variable.. Any suggestion on this?
Please help. UTF-8 conversion is also not working on special characters
Yeah, it should use Encoding.UTF8 instead of Encoding.ASCII. For example, in this fragment
var t1 = @”□(p→q)”;
var tbytes = Encoding.UTF8.GetBytes(t1);
var tstream = new MemoryStream(tbytes);
var treader = new StreamReader(tstream);
var t2 = treader.ReadToEnd();
var roundTrip = t1 == t2;
roundTrip will end up true, but false if you use the ASCII encoding (the special characters convert to ?).
It’s better to use StringReader and StringWriter.
Thanks @Shack Toms,rliviu.
actually mistake that i was doing is to read string line by line i was using streamreader n that requires encode or decode. Now instead of streamreader i am using stringreader. and without any encode or decode my code is working fine.
I prefer to have an extension method for this:
public static Stream ToStream(this String str)
{
return new MemoryStream(System.Text.Encoding.Default.GetBytes(str));
}
On behalf of @Peter, who either portrayed the presumptuous troll or hid from shame, I would like to say “My bad!” for the publication date oversight which he/she never referenced and @timm resolved.
My thanks go out to @timm for publishing this fine example of code.
very useful information for me.
Check this one…C# memory stream to file.
http://net-informations.com/q/faq/memory.html
Balmer