2010-09-28 46 views
12

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

回答

26

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

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

你可以改变UTF16是你想用它来传递字符串什么编码。

+0

这是工作,谢谢。 – mohang 2010-09-28 12:57:41

+0

在第2行添加缺少的右括号。我无法编辑,因为编辑需要更改超过6个字符... – cudahead 2012-11-30 09:34:43

+0

@cudahead:谢谢,完成。 – 2012-11-30 12:39:21

1

假设您想要的字符串的流编码UTF8:

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

取决于你真正想做的事,你可能会得到更好的使用StringReader类服务。它不是一个IO.Stream,但它使得易于面向文本的字符串读取成为可能。

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);