我需要调用一个接受stream参数的方法。该方法将文本加载到流中,该流通常是文件。我想简单地用流的内容填充一个字符串,而不是将其写入文件。我该怎么做?
答案 0 :(得分:7)
将MemoryStream与StreamReader一起使用。类似的东西:
using (MemoryStream ms = new MemoryStream())
using (StreamReader sr = new StreamReader(ms))
{
// pass the memory stream to method
ms.Seek(0, SeekOrigin.Begin); // added from itsmatt
string s = sr.ReadToEnd();
}
答案 1 :(得分:5)
使用StringWriter充当字符串的流:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
CallYourMethodWhichWritesToYourStream(sw);
return sb.ToString();
答案 2 :(得分:2)
查找MemoryStream类
答案 3 :(得分:2)
MemoryStream ms = new MemoryStream();
YourFunc(ms);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string mystring = sr.ReadToEnd();
是一种方法。
答案 4 :(得分:0)
你可以这样做:
string s = "Wahoo!";
int n = 452;
using( Stream stream = new MemoryStream() ) {
// Write to the stream
byte[] bytes1 = UnicodeEncoding.Unicode.GetBytes(s);
byte[] bytes2 = BitConverter.GetBytes(n);
stream.Write(bytes1, 0, bytes1.Length);
stream.Write(bytes2, 0, bytes2.Length);