C#Memorystream未完全保存到文件中

时间:2017-06-07 13:31:53

标签: c# streamwriter memorystream

我使用MemoryStreamStreamWriter将对象导出到csv。但保存文件后,我发现文件的末尾丢失了。它在一条线的中间切割。

以下是我的代码:

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();
    }
}

这是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);
}

2 个答案:

答案 0 :(得分:3)

首先sw.Flush(),然后执行FileSystem.AddFile()StreamWriter可能在将输出传递给MemoryStream之前缓冲输出。

答案 1 :(得分:0)

您需要先刷新StreamWriter,然后从流中创建文件。