1

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

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

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

如果你能帮助我或给我另一个想法,我会很高兴听到。

4

1 回答 1

1

我的解决方案:

    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;
    }
于 2012-06-11T06:41:53.153 回答