将字符串转换为System.IO.Stream

本文关键字:IO Stream System 字符串 转换 | 更新日期: 2023-09-27 18:13:41

我需要将String转换为System.IO.Stream类型以传递给另一个方法。

I try this unsuccessfully.

Stream stream = new StringReader(contents);

将字符串转换为System.IO.Stream

试试这个:

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

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

要将字符串转换为流,您需要决定流中的字节应该使用哪种编码来表示该字符串-例如您可以:

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

MSDN引用:

  • http://msdn.microsoft.com/en-us/library/ds4kkd55%28v=VS.100%29.aspx
  • http://msdn.microsoft.com/en-us/library/e55f3s5k.aspx
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);

这是旧的,但帮助:

也可以使用stringReader流

string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );