我有一些已经停止工作的代码。它本身并没有改变,但它已经停止工作了。
它涉及使用内存流从应用程序外部导入一些文本数据,并将其传递给应用程序,最终将文本转换为字符串。下面的代码片段封装了这个问题:
[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.
}我是不是遗漏了什么?“文本”应该具有原始的价值,而且直到今天它一直如此,这意味着我拥有的东西是脆弱的,但我做错了什么呢?
提亚
发布于 2013-09-27 14:36:12
您忘记了流的当前位置。将"x,y,z“数据写入流后,流的位置将指向数据的末尾。您需要将流的位置移回读出数据。就像这样:
static void stuff2(Stream ms)
{
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
stuff3(sr.ReadToEnd());
}
}发布于 2013-09-27 14:37:14
你必须“重置”你的记忆流。将代码更改为:
[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();
stream.Seek(0, SeekOrigin.Begin);
stuff2(ms);
}
}
}https://stackoverflow.com/questions/19053367
复制相似问题