在Zip中下载文件

时间:2015-06-19 08:35:38

标签: asp.net-mvc-4

我想以zip格式下载文件,但是我的代码出错并且错误如下所示

我的代码:

        using (ZipFile zip = new ZipFile())
        {

            zip.AlternateEncodingUsage = ZipOption.AsNecessary;
            zip.AddDirectoryByName("Files");
            //foreach (GridViewRow row in GridView1.Rows)
            //{
            //    if ((row.FindControl("chkSelect") as CheckBox).Checked)
            //    {
            //        string filePath = (row.FindControl("lblFilePath") as Label).Text;
            //        zip.AddFile(filePath, "Files");
            //    }
            //}
            DirectoryInfo directory = new DirectoryInfo(Server.MapPath(@"~\Election\Latur"));
            var files = directory.GetFiles().ToList();                
            foreach (var file in files)
            {
                zip.AddFile(file.ToString(),"Files");
            }
            Response.Clear();
            Response.BufferOutput = false;
            string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
            zip.Save(Response.OutputStream);
            Response.End();
        }

当我在zip上使用上面的代码下载文件然后发生错误

错误

enter image description here

2 个答案:

答案 0 :(得分:0)

导致此错误的原因有两种:

1-目录“文件”无法创建(拒绝权限) 2-无法获取文件到“〜\ Election \ Latur”

无论如何:             var files = directory.GetFiles()。ToList();
            foreach(文件中的var文件)

我认为类型var对此不正确。使用base64编码器的字符串更正确。

答案 1 :(得分:0)

using (ZipFile zip = new ZipFile())
    {
         string folderpath = Server.MapPath(@"~\Election\Latur\");
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
        zip.AddDirectoryByName("Files");

        DirectoryInfo directory = new DirectoryInfo(Server.MapPath(@"~\Election\Latur"));
        var files = directory.GetFiles().ToList();                
        foreach (var file in files)
        {
           var filepath = folderpath + file.ToString();
           zip.AddFile(filepath,"Files");

        }
        Response.Clear();
        Response.BufferOutput = false;
        string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        zip.Save(Response.OutputStream);
        Response.End();
    }