200

I need to convert a String to System.IO.Stream type to pass to another method.

I tried this unsuccessfully.

Stream stream = new StringReader(contents);
xbonez
  • 40,730
  • 48
  • 157
  • 236

5 Answers5

428

Try this:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);

and

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Marco
  • 55,302
  • 13
  • 128
  • 150
  • Thanks. I wasn't aware MemoryStream was the same as Stream. – xbonez Nov 08 '11 at 07:29
  • 6
    @xbonez: `Stream` is not the same as `MemoryStream`. `MemoryStream` inherits from `Stream`, just like `FileStream`. So you can cast them as `Stream`... – Marco Nov 08 '11 at 07:31
  • 20
    Just a note: Streams implement IDisposable, so you need a using wrapper around them to be safe. – Steve Hibbert May 23 '14 at 11:32
49

To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:

MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );

MSDN references:

Yahia
  • 68,257
  • 8
  • 107
  • 138
7
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
Sandeep Pathak
  • 10,258
  • 7
  • 42
  • 57
-1
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
kprobst
  • 15,555
  • 5
  • 30
  • 53
-8

this is old but for help :

you can also use the stringReader stream

string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
bensiu
  • 22,720
  • 51
  • 71
  • 112
zetoff
  • 89
  • 1
  • 1