我需要调用一个接受stream参数的方法.该方法将文本加载到流中,该流通常是文件.我想简单地用流的内容填充一个字符串,而不是将其写入文件.我该怎么做呢?
将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(); }
使用StringWriter充当字符串的流:
StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); CallYourMethodWhichWritesToYourStream(sw); return sb.ToString();