Convert string to Stream

R

Robert Strickland

What is the best way to convert a variable of type string to the IO.Stream
object?
 
M

mikeb

Robert said:
What is the best way to convert a variable of type string to the IO.Stream
object?

Assuming you want the string's stream encoded in UTF8:

System.IO.MemoryStream = new System.IO.MemoryStream(
System.Text.Encoding.UTF8.GetBytes( "the string"));

Depending on what you really want to do, you might be better served
using the StringReader class. It's not an IO.Stream, but it makes for
easy text-oriented reading of a string.
 
R

Robert Strickland

That worked - thanks

mikeb said:
Assuming you want the string's stream encoded in UTF8:

System.IO.MemoryStream = new System.IO.MemoryStream(
System.Text.Encoding.UTF8.GetBytes( "the string"));

Depending on what you really want to do, you might be better served
using the StringReader class. It's not an IO.Stream, but it makes for
easy text-oriented reading of a string.
 
R

Robert Strickland

Thanks for your help. I have one more question. I need to reverse the
process - convert something typed as stream to string.

Thanks again
 
M

mikeb

Robert said:
Thanks for your help. I have one more question. I need to reverse the
process - convert something typed as stream to string.

Once again, this assumes that your encoding is UTF8 - you'll need to use
a difference StreamReader() constructor if the encoding is different.

=====================================================
System.IO.StreamReader sr = new System.IO.StreamReader( yourStreamObj);

string s = sr.ReadToEnd();
=====================================================

Eric Gunnerson has a good article on stream IO basics:


http://msdn.microsoft.com/library/en-us/dncscol/html/csharp01162003.asp

Thanks again
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top