如何从String对象获取System.IO.Stream

时间:2010-09-28 12:48:25

标签: c# string

我有字符串对象。我需要将此数据传递给另一个XYZ类型的对象。但是XYZ类型的这个对象只采用System.IO.Stream。那么如何将字符串数据转换为流,以便XYZ类型的对象可以使用此字符串数据?

3 个答案:

答案 0 :(得分:26)

您必须选择要用于将字符串转换为字节数组的文本编码,然后使用MemoryStream来调用您的函数。例如:

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

您可以将UTF16更改为您要用来传递字符串的任何编码。

答案 1 :(得分:1)

假设您希望以UTF8编码字符串的流:

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

根据您真正想做的事情,使用StringReader类可能会更好。它不是IO.Stream,但它可以轻松读取字符串的文本。

答案 2 :(得分:1)

此代码将格式化文本(rtf)加载到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);