c#内存流到文本文件未完成
本文关键字:文件 未完成 文本 内存 | 更新日期: 2023-09-27 18:03:27
我在c#中使用大型文本文件函数的内存流时遇到了问题。输出文本文件不包含所有信息,它缺少我在streamwriter中写入的最后几行文本。
许多帖子说使用stream.flush()并使用stream将流重置到流的开始。查找(0,seekOrigin.End),但两者似乎都没有区别。
代码如下:
using (var stream = new MemoryStream())
{
using (var sb = new StreamWriter(stream))
{
Decimal[,] oparray = new decimal[477, 521];
List<Rech_RCH_Result> result1;
//RCH File Header
sb.WriteLine("#MODFLOW2000 Recharge Package");
sb.WriteLine("PARAMETER 0");
sb.WriteLine(" 1 50");
for (int sp = 1; sp < 3; sp++) //should be 209
{
ObjectResult<Rech_RCH_Result> qryRCH = db.Rech_RCH(NRD, sp);
result1 = qryRCH.Select(p => new Rech_RCH_Result { M_Col = p.M_Col, M_row = p.M_row, Recharge = p.Recharge, StressPeriod = p.StressPeriod }).ToList();
//Stress Period Header for SP
sb.WriteLine(" 1 1");
sb.WriteLine(" 18 1.000(10e15.6) -1 RECHARGE");
//model row = 1 to 476, col = 1 to 520
foreach (Rech_RCH_Result s in result1)
{
oparray[s.M_row.Value, s.M_Col.Value] = s.Recharge;
}
for (int x = 1; x < 477; x++)
{
for (int y = 1; y <= 520; y += 10)
{
//write out values in chunks of 10
sb.WriteLine(string.Format(" {0:0.000000E+00} {1:0.000000E+00} {2:0.000000E+00} {3:0.000000E+00} {4:0.000000E+00} {5:0.000000E+00} {6:0.000000E+00} {7:0.000000E+00} {8:0.000000E+00} {9:0.000000E+00}", oparray[x, y], oparray[x, y + 1], oparray[x, y + 2], oparray[x, y + 3], oparray[x, y + 4], oparray[x, y + 5], oparray[x, y + 6], oparray[x, y + 7], oparray[x, y + 8], oparray[x, y + 9]));
}
}
Array.Clear(oparray, 0, oparray.Length);
}
stream.Flush();
//Looks like the stream is not completing and missing a few lines.
//stream.Seek(0, SeekOrigin.Begin);
stream.Seek(0, SeekOrigin.End);
using (FileStream file = System.IO.File.Create(Server.MapPath(string.Format("~/RCHFiles/{0}.txt", filename))))
{
stream.WriteTo(file);
}
//using (ZipFile zip = new ZipFile())
//{
// zip.AddEntry(filename + ".RCH", stream);
// zip.Save(Server.MapPath(string.Format("~/RCHFiles/{0}.zip", filename)));
//}
}
}
您正在冲洗MemoryStream
,而不是StreamWriter
。这可能是缓冲
将stream.Flush()
替换为sb.Flush()
。(刷新MemoryStream
不做任何事情)
还请注意,您可以使用MemoryStream.CopyTo
而不是Stream.WriteTo
而不使用倒带。