首页 > 解决方案 > Trying to Download File(s) from a List variable into a zip file

问题描述

So as the question states i am trying to download files from a List variable that I am storing filepaths from the database

I am grabbing the paths from the db and storing them in allPaths

using (var db = new Db())
{
    // Get Specific years and months
    allPaths = db.ClientStatement_Inventory
        .Where(x => 
            x.accountNum == acctNum && 
            years.Contains(x.statementYear) && 
            months.Contains(x.statementMonth))
        .Select(c => c.statementPath)
        .ToList();
}

I am then trying to download the files that are stored in allPaths variable like so: When it is hitting my memorystream i am getting an error:

ReadTimeout = 'memoryStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

And then when it hits my ZipArchive using statement it is giving me this error:

Entries = 'archive.Entries' threw an exception of type 'System.NotSupportedException'

using (var memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        for (int i = 0; i < allPaths.Count; i++)
        {
            archive.CreateEntryFromFile(allPaths[i], allPaths[i]);
        }
    }

    return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
}

I honestly have no idea if I am even remotely doing this right but I have been taking pieces from different Stack Overflow questions and Google but cannot get anything to work.

标签: c#asp.net-mvcsystem.io.file

解决方案


如果您只是尝试压缩所有文件并保存到磁盘,则应该这样做。

using (var memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        for (int i = 0; i < allPaths.Count; i++)
        {
            archive.CreateEntryFromFile(allPaths[i], allPaths[i]);
        }
    }

    using (var fileStream = new FileStream(@"All.zip", FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

推荐阅读