asp.net-mvc-3 - 将 FileContentResult 文件导出为 ZIP

标签 asp.net-mvc-3 zip

我使用C#-MVC3。我有一个“导出”页面。我有一些用于从数据库导出不同表的函数,每个函数从表中创建一个 CSV 文件并将 FileContentResult 文件返回给用户。

现在我想创建一个“全部导出”按钮,以一次下载所有文件。 我尝试使用 ZipFile,但它仅获取文件名和路径 - 保存在服务器上的文件,而不是“FileContentResult”文件。

所以我想将“FileContentResult”文件临时保存在服务器上,压缩它们并删除它们 - 但我找不到如何保存“FileContentResult”文件。

如果您可以帮助我或给我其他想法,我很高兴听到。

最佳答案

我的解决方案:

    public ZipFile DownloadAllToZip()
    {
        string path = "c:\\TempCSV";
        try
        {
            if (Directory.Exists(path))
            {
                EmptyFolder(path);
            }
            else
            {
                DirectoryInfo di = Directory.CreateDirectory(path);
            }
            List<FileContentResult> filesToExport = GetAllCSVs();

            foreach (var file in filesToExport)
            {
                try
                {
                    using (FileStream stream = new FileStream(path + "\\" + file.FileDownloadName, FileMode.CreateNew))
                    {
                        using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                        {
                            byte[] buffer = file.FileContents;
                            stream.Write(buffer, 0, buffer.Length);
                            writer.Close();
                        }
                    }
                }
                catch { }
            }
        }
        catch{ }

        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=MaterialAssetTracker.zip");
        ZipFile zip= new ZipFile();
        using (zip)
        {
            zip.CompressionLevel = CompressionLevel.None;
            zip.AddSelectedFiles("*.csv", path + "\\", "", false);
            zip.Save(Response.OutputStream);
        }
        Response.Close();
        EmptyFolder(path);
        return zip;
    }

关于asp.net-mvc-3 - 将 FileContentResult 文件导出为 ZIP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672991/

相关文章:

java - 从 InputStream 解压缩文件并返回另一个 InputStream

c# - 在 ASP.NET MVC 3 中使用 View 模型

c# - 在 Asp.Net MVC 3 中,什么构成 AuthorizeAttribute 的经过身份验证的用户?

View 上所有按钮/链接点击或下拉更改的 jQuery 事件

java - 以编程方式在 Zip 文件中创建链接 - java

c# - Java ZIP 文件从一个 zip 复制并粘贴到另一个 zip

c# - 数据注释 - DisplayFormat - 格式化数字字符串

facebook - MVC3 Web 项目错误 : "An attempt was made to access a socket in a way forbidden by its access permissions 10.10.0.1:3128"

java - 如何通过响应 OutputStream 将 zip 文件返回给浏览器?

c# - 试图弄清楚这个数据库文件是否有压缩数据