ASP.NET 打包下载文件

使用的类库为:ICSharpCode.SharpZipLib.dll

一种是打包整个文件夹,另一种是打包指定的多个文件,大同小异:

using ICSharpCode.SharpZipLib.Zip;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 打包下载某文件夹里的所有文件

        //需要打包的文件夹
        string path = "UploadImage/Images/";
        string serverPath = Server.MapPath(path);

        //创建临时文件夹
        string tempName = DateTime.Now.ToString("yyyyMMddHHMMss");
        string tempFolder = Path.Combine(serverPath, tempName);
        Directory.CreateDirectory(tempFolder);

        //遍历文件夹中所有的文件到临时文件夹中
        DirectoryInfo folder = new DirectoryInfo(serverPath);
        foreach (FileInfo file in folder.GetFiles())
        {
            string filename = file.Name;
            File.Copy(serverPath + "/" + filename, tempFolder + "/" + filename);
        }

        //压缩文件
        compressFiles(tempFolder, tempFolder + "\\" + tempName + ".rar");
        //下载文件
        // DownloadRAR(tempFolder + "\\" + tempName + ".rar", "这里下载文件重命名后的名称");


        //某些文件打包下载
        DownLodeSum();

    }

    /// <summary>
    /// 某些文件打包下载
    /// </summary>
    public void DownLodeSum()
    {
        //临时文件夹所在目录
        string path = "UploadImage/";
        string serverPath = Server.MapPath(path);

        //创建临时文件夹
        string tempName = DateTime.Now.ToString("yyyyMMddHHMMss");
        string tempFolder = Path.Combine(serverPath, tempName);
        Directory.CreateDirectory(tempFolder);

        //复制需要压缩的文件到临时文件夹中
        File.Copy(Server.MapPath("UploadImage/Images/bg-b.png"), Server.MapPath(path + tempName + "/bg-b.png"));
        File.Copy(Server.MapPath("UploadImage/Images/bg-j.png"), Server.MapPath(path + tempName + "/bg-j.png"));
        File.Copy(Server.MapPath("UploadImage/Images/icon-cart.png"), Server.MapPath(path + tempName + "/icon-cart.png"));

        //压缩文件
        compressFiles(tempFolder, tempFolder + "\\" + tempName + ".rar");
        //下载文件
        DownloadRAR(tempFolder + "\\" + tempName + ".rar", "这里下载文件重命名后的名称");

    }

    /// <summary>
    /// 压缩文件
    /// </summary>
    /// <param name="dir">文件目录</param>
    /// <param name="zipfilename">zip文件名</param>
    public static void compressFiles(string dir, string zipfilename)
    {
        if (!Directory.Exists(dir))
        {
            return;
        }
        try
        {
            string[] filenames = Directory.GetFiles(dir);
            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename)))
            {

                s.SetLevel(9); // 0 - store only to 9 - means best compression

                byte[] buffer = new byte[4096];

                foreach (string file in filenames)
                {
                    ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(file))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }
                s.Finish();
                s.Close();
            }
        }
        catch
        {

        }
    }

    /// <summary>
    /// 下载生成的RAR文件
    /// </summary>
    private void DownloadRAR(string file, string name)
    {
        FileInfo fileInfo = new FileInfo(file);
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment;filename=" + name + ".rar");
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.AddHeader("Content-Transfer-Encoding", "binary");
        Response.ContentType = "application/octet-stream";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        Response.WriteFile(fileInfo.FullName);
        Response.Flush();
        string tempPath = file.Substring(0, file.LastIndexOf("\\"));
        //删除临时目录下的所有文件
        DeleteFiles(tempPath);
        //删除空目录
        Directory.Delete(tempPath);
        Response.End();
    }

    /// <summary>
    /// 删除临时目录下的所有文件
    /// </summary>
    /// <param name="tempPath">临时目录路径</param>
    private void DeleteFiles(string tempPath)
    {
        DirectoryInfo directory = new DirectoryInfo(tempPath);
        try
        {
            foreach (FileInfo file in directory.GetFiles())
            {
                if (file.Attributes.ToString().IndexOf("ReadOnly") != -1)
                {
                    file.Attributes = FileAttributes.Normal;
                }
                File.Delete(file.FullName);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}
原文地址:https://www.cnblogs.com/BrokenIce/p/6803712.html