使用多个文件C#

时间:2018-10-25 17:17:44

标签: c# asp.net-mvc zip memorystream

我正在从互联网上下载的文件(以字节为单位)创建一个Zip文件,[ 但是我有一个问题,我不知道我在做什么错...我生成了zip文件,但文件已损坏,文件大小正确(不为0)。 请问你能帮帮我吗? 也许我不太了解。

public <ActionResult> SomeFunction()
{
    var invoices = GetInvoices();
    WebClient client = new WebClient();
    byte[] zipBytes = null;

    using (var compressedFileStream = new MemoryStream())
    {
        using (ZipArchive zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, leaveOpen: true))
        {
            foreach (var invoice in invoices)
            {
                // This has correct values.
                byte[] fileBytes = client.DownloadData(invoice.XmlUri);

                // Create the instance of the file.
                var zipEntry = zipArchive.CreateEntry(invoice.XmlFileName);

                // Get the stream of the file.
                using (var entryStream = new MemoryStream(fileBytes))

                // Get the Stream of the zipEntry
                using (var zipEntryStream = zipEntry.Open())
                {
                    // Adding the file to the zip file.
                    entryStream.CopyTo(zipEntryStream);
                }
            }
        }
        zipBytes = compressedFileStream.ToArray();
    }
    return File(zipBytes , System.Net.Mime.MediaTypeNames.Application.Octet, "test.zip");
}

1 个答案:

答案 0 :(得分:0)

移动

zipBytes = compressedFileStream.ToArray();

处理完归档文件后的“ To”,以便将所有数据刷新到基础流。

public <ActionResult> SomeFunction() {
    var invoices = GetInvoices();
    WebClient client = new WebClient();
    byte[] zipBytes = null;

    using (var compressedFileStream = new MemoryStream()) {
        using (ZipArchive zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, leaveOpen: true)) {
            foreach (var invoice in invoices) {
                // This has correct values.
                byte[] fileBytes = client.DownloadData(invoice.XmlUri);

                // Create the instance of the file.
                var zipEntry = zipArchive.CreateEntry(invoice.XmlFileName);

                // Get the stream of the file.
                using (var entryStream = new MemoryStream(fileBytes))

                // Get the Stream of the zipEntry
                using (var zipEntryStream = zipEntry.Open()) {
                    // Adding the file to the zip file.
                    entryStream.CopyTo(zipEntryStream);
                }
            }            
        }
        zipBytes = compressedFileStream.ToArray();
    }
    return File(zipBytes , System.Net.Mime.MediaTypeNames.Application.Octet, "test.zip");
}
  

引用ZipArchive.Dispose()

     

此方法完成了归档文件的编写,并释放了ZipArchive对象使用的所有资源。   除非您使用ZipArchive(Stream, ZipArchiveMode, Boolean)构造函数重载来构造对象,并将其leaveOpen参数设置为true,否则所有基础流都将关闭,并且不再可用于后续的写操作。

     

完成使用此ZipArchive实例后,请调用Dispose()释放该实例使用的所有资源。您应该删除对此ZipArchive实例的进一步引用,以使垃圾回收器可以回收该实例的内存,而不是保留该实例以进行最终化。