Convert string to Stream

  • Thread starter Thread starter Robert Strickland
  • Start date Start date
R

Robert Strickland

What is the best way to convert a variable of type string to the IO.Stream
object?
 
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.
 
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.
 
Thanks for your help. I have one more question. I need to reverse the
process - convert something typed as stream to string.

Thanks again
 
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
 
Back
Top