217

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);
Ayush
  • 41,754
  • 51
  • 164
  • 239

5 Answers5

457

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
  • 56,740
  • 14
  • 129
  • 152
  • Thanks. I wasn't aware MemoryStream was the same as Stream. – Ayush Nov 08 '11 at 07:29
  • 7
    @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
  • 23
    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
55

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
  • 69,653
  • 9
  • 115
  • 144
9
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
0
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
kprobst
  • 16,165
  • 5
  • 32
  • 53
-8

this is old but for help :

you can also use the stringReader stream

string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
bensiu
  • 24,660
  • 56
  • 77
  • 117
zetoff
  • 89
  • 1
  • 1