[英]C# Memorystream is not fully saved to the file
I am exporting an object to csv using MemoryStream
and StreamWriter
. 我正在使用
MemoryStream
和StreamWriter
将对象导出到csv。 But after saving the file, I see that the end of the file is missing. 但是保存文件后,我看到文件末尾丢失了。 Its cut of in the middle of a line.
它在一行中间被剪切。
Below is my code: 下面是我的代码:
public void Export(ProductExport productExport)
{
var country = (Country)(int.Parse(productExport.Firma.Code));
using(var stream = new MemoryStream())
{
var sw = new StreamWriter(stream);
// Write header row
sw.WriteLine(
"{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
"Groep",
"TecDoc Leverancier",
"TecDoc Ref",
"SA",
"EAN",
"Omschrijving NL",
"V/E",
"VPE",
"Prijs per",
"Bruto prijs"
);
foreach(var product in productExport.Products)
{
// Write header row
sw.WriteLine(
"{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
product.Artgrp,
product.TecDoc != null ? product.TecDoc.Supplier : "",
product.TecDoc != null ? product.TecDoc.Value : "",
product.Ids.Where<Id>(i => i.Type == "SA").Select(i => i.Value).DefaultIfEmpty("").First(),
product.Ids.Where<Id>(i => i.Type == "EN").Select(i => i.Value).DefaultIfEmpty("").First(),
product.Descriptions.Where<Description>(d => d.Lang == "NL").Select(i => i.Value).DefaultIfEmpty("").First(),
product.SalesUnit,
product.PackingUnit.Value,
product.PriceUnit.Value,
product.Prices.First<Price>(p => p.Type == "BR" && p.Country == country.ToString()).Value
);
}
FileSystem.AddFile(country + "-" + String.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv", stream);
sw.Flush();
}
}
And this is the code of the FileSystem.AddFile()
function: 这是
FileSystem.AddFile()
函数的代码:
public void AddFile(string path, System.IO.Stream stream)
{
var fullPath = GetFullPath(path);
var directory = Path.GetDirectoryName(fullPath);
if (directory == null) throw new InvalidOperationException("Can't get the directory.");
Directory.CreateDirectory(directory); // Make sure the directory is created!
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
using (var destination = (Stream)File.Create(fullPath))
stream.CopyTo(destination);
}
First sw.Flush()
, then do the FileSystem.AddFile()
. 首先
sw.Flush()
,然后执行FileSystem.AddFile()
。 The StreamWriter
is probably buffering the output before passing it to the MemoryStream
. StreamWriter
可能在将输出传递给MemoryStream
之前先对其进行缓冲。
您需要先刷新StreamWriter
,然后再从流中创建文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.