繁体   English   中英

C#Memorystream没有完全保存到文件

[英]C# Memorystream is not fully saved to the file

我正在使用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);
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM