首页 > 解决方案 > C# Response.OutputStream 损坏下载的文件

问题描述

在此处输入图像描述我正在尝试创建动态创建的可下载 ZIP 文件。这些文件是在服务器上正确创建的,但是当它们使用“Response.OutputStream”发送到客户端时,文件会损坏。这似乎仅在 zip 文件超过 4GB 时发生。有谁知道这是为什么?

我使用的确切代码是:

       string path = @"C:\temp\vid";

        Response.BufferOutput = false; // Disable Buffer Output to start the download immediately

        // Set custom headers to force browser to download the file instad of trying to open it
        Response.ContentType = "application/x-zip-compressed";
        Response.AppendHeader("content-disposition", "attachment; filename=Archive.zip");

        ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream, 20000);
        zipOutputStream.SetLevel(0); // No compression
        zipOutputStream.UseZip64 = UseZip64.On;//Forces Zip64 to be used
        zipOutputStream.IsStreamOwner = true;

        try
        {
            foreach (string file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
            {
                using (var fs = System.IO.File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    ZipEntry entry = new ZipEntry(ZipEntry.CleanName(Path.GetFileName(file))); //Create zip compatible name
                    zipOutputStream.PutNextEntry(entry); //Adds entry to list

                    fs.CopyTo(zipOutputStream);

                    zipOutputStream.CloseEntry();
                    zipOutputStream.Flush();

                    Response.Flush();
                    Response.Clear();
                }
            }

            zipOutputStream.Finish();
            zipOutputStream.Close();
            Response.End();
            Response.Flush();

        }
        catch
        {
            Debug.WriteLine("Connection Closed or error");
        }

        return new HttpStatusCodeResult(HttpStatusCode.OK);

标签: c#asp.net

解决方案


推荐阅读