我有一些代码已停止工作。它本身并没有改变,但它已经停止工作。
它涉及使用内存流从应用程序外部导入一些文本数据并将其传递给应用程序,最终将文本转换为字符串。以下代码片段概括了该问题:
[TestMethod]
public void stuff()
{
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms))
{
sw.Write("x,y,z"); //"x,y,z" is usually a line of string data from a textfile
sw.Flush();
stuff2(ms);
}
}
}
void stuff2(Stream ms)
{
using (var sr = new StreamReader(ms))
{
stuff3(sr.ReadToEnd());
}
}
void stuff3(string text)
{
var x = text; //when we get here, 'text' is an empty string.
}
我错过了什么吗? “文本”应该具有原始值,直到今天它总是如此,这表明我拥有的 odne 是脆弱的,但我做错了什么?
TIA
最佳答案
您忘记了流的当前位置。将“x,y,z”数据写入流后,流的位置将指向数据的末尾。您需要将流的位置移回才能读出数据。像这样:
static void stuff2(Stream ms)
{
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
stuff3(sr.ReadToEnd());
}
}
关于c# - 内存流之谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19053367/