简体   繁体   中英

C# Memorystream is not fully saved to the file

I am exporting an object to csv using MemoryStream and StreamWriter . 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:

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() . The StreamWriter is probably buffering the output before passing it to the MemoryStream .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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