[英]MemoryStream mystery
我有一些已停止工作的代碼。 它本身並沒有改變,但是已經停止工作。
它涉及到使用內存流從應用程序外部導入一些文本數據並將其傳遞給應用程序,最終將文本轉換為字符串。 以下代碼片段封裝了該問題:
[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.
}
我想念什么嗎? “文本”應該具有原始價值,並且直到今天一直神秘地一直存在,這表明我的特長是脆弱的,但是我在做什么錯呢?
TIA
您忘記了流的當前位置。 將“ x,y,z”數據寫入流后,流的位置將指向數據的末尾。 您需要移回流的位置以讀出數據。 像這樣:
static void stuff2(Stream ms)
{
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
stuff3(sr.ReadToEnd());
}
}
您必須“重置”您的內存流。 將您的代碼更改為:
[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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.