12

I have string object. I need to pass this data to another object of type XYZ. But this object of type XYZ is taking only System.IO.Stream. So how to convert the string data into a stream so that object of XYZ type can use this string data?

3 Answers 3

26

You'll have to pick a text encoding to use to translate the string into a byte array, then use a MemoryStream to call your function. For example:

using(System.IO.MemoryStream ms = new System.IO.MemoryStream( System.Text.Encoding.UTF16.GetBytes(yourString))) { XYZ(ms); } 

You can alter UTF16 to be whatever encoding you'd like to use to pass the string.

Sign up to request clarification or add additional context in comments.

1 Comment

add missing right parenthesis in row 2. I could not edit, because edits need to change more than 6 characters...
1

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

System.IO.MemoryStream mStream = 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.

Comments

1

This code loads formatted text (rtf) into RichTextBox

TextRange tr = new TextRange(RichTextBox1.Document.ContentStart,RichTextBox1.Document.ContentEnd); string s = myStringData; //myStringData is a string in some format - rtf, xml, etc.. MemoryStream ms = new MemoryStream(s); tr.Load(ms, DataFormats.Rtf); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.