您的位置:首页 > 编程语言 > C#

多文件打包压缩、下载类--使用第三方控件ICSharpCode

2010-08-01 20:23 507 查看
 //引用了第三方控件ICSharpCode

 //using ICSharpCode.SharpZipLib.Zip;

    /// <summary>
    /// 多文件打包压缩类
    /// 使用第三方控件ICSharpCode
    /// </summary>
    public class FiledownloadControl
    {
        #region private method

        /// <summary>
        /// Gets the directory files.
        /// </summary>
        /// <param name="strParentDirectoryPath">The parent directory path.</param>
        /// <param name="AllFilesPath">All files path.</param>
        private void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath)
        {
            string[] files = Directory.GetFiles(strParentDirectoryPath);
            for (int i = 0; i < files.Length; i++)
            {
                AllFilesPath.Add(files[i]);
            }//for
            string[] directorys = Directory.GetDirectories(strParentDirectoryPath);
            for (int i = 0; i < directorys.Length; i++)
            {
                GetDirectoryFiles(directorys[i], AllFilesPath);
            }//for
            if (files.Length == 0 && directorys.Length == 0) //empty folder
            {
                AllFilesPath.Add(strParentDirectoryPath);
            }//if
        }//GetDirectoryFiles

        /// <summary>
        /// 重置被压缩文件或文件夹名并压缩
        /// </summary>
        /// <param name="strZipTopDirectoryPath">string 被压缩文件或文件夹的路径</param>
        /// <param name="zipOutputStream">ZipOutputStream 压缩流</param>
        /// <param name="strFile">string 被压缩文件或文件夹名</param>
        private void ZipFileorDirectory(string strZipTopDirectoryPath, ZipOutputStream zipOutputStream, string strFile)
        {
            string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
            if (strFileName.StartsWith(""))
            {
                strFileName = strFileName.Substring(1);
            }
            ZipEntry entry = new ZipEntry(strFileName);
            entry.DateTime = DateTime.Now;
            zipOutputStream.PutNextEntry(entry);
        }//ZipFileorDirectory

        /// <summary>
        /// 压缩文件或文件夹
        /// </summary>
        /// <param name="strZipPath">string 压缩后生成的压缩文件全名</param>
        /// <param name="strZipTopDirectoryPath">string被压缩文件的上级目录</param>
        /// <param name="intZipLevel">int 压缩级数</param>
        /// <param name="strPassword">string 压缩文件的解压密码</param>
        /// <param name="filesOrDirectoriesPaths">string[] 目标文件/文件夹数组</param>
        /// <returns>bool 是否压缩文件成功</returns>
        private bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths)
        {
            try
            {
                List<string> AllFilesPath = new List<string>();
                //将目标文件存储在集合中
                if (filesOrDirectoriesPaths.Length > 0)
                {
                    for (int i = 0; i < filesOrDirectoriesPaths.Length; i++)
                    {
                        //单个文件直接存储
                        if (File.Exists(filesOrDirectoriesPaths[i]))
                        {
                            AllFilesPath.Add(filesOrDirectoriesPaths[i]);
                        }//if
                        //文件夹则调用文件夹存储方法
                        else if (Directory.Exists(filesOrDirectoriesPaths[i]))
                        {
                            //调用文件夹存储方法
                            GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath);
                        }//else if
                    }//for
                }//if
                //将集合中的文件打包压缩到提供的压缩文件中
                if (AllFilesPath.Count > 0)
                {
                    ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(strZipPath));
                    zipOutputStream.SetLevel(intZipLevel);
                    zipOutputStream.Password = strPassword;

                    for (int i = 0; i < AllFilesPath.Count; i++)
                    {
                        string strFile = AllFilesPath[i].ToString();
                        try
                        {
                            //直接压缩文件夹
                            if (strFile.Substring(strFile.Length - 1) == "")
                            {
                                //重置被压缩文件或文件夹名并压缩
                                ZipFileorDirectory(strZipTopDirectoryPath, zipOutputStream, strFile);
                            }//if
                            //通过文件流压缩文件
                            else
                            {
                                FileStream fs = File.OpenRead(strFile);   
                                //重置被压缩文件或文件夹名并压缩
                                ZipFileorDirectory(strZipTopDirectoryPath, zipOutputStream, strFile);
                                //文件长度过长,则分段读取
                                for (long j = 0; j < fs.Length; j += 65536)
                                {
                                    //每次读取64K
                                    int byteLength = 65536;
                                    if ((fs.Length - j) < 65536)
                                    {
                                        byteLength = (int)(fs.Length - j);
                                    } //if

                                    byte[] buffer = new byte[byteLength];
                                    fs.Read(buffer, 0, byteLength);
                                    zipOutputStream.Write(buffer, 0, byteLength);
                                } //for
                                fs.Close();
                                fs.Dispose();
                            }//else
                        }//try
                        catch
                        {
                            continue;
                        }//catch
                    }//for                   
                    zipOutputStream.Finish();
                    zipOutputStream.Close();
                    //压缩完成,返回 true
                    return true;
                }//if
                else
                {
                    //压缩失败,返回 false
                    return false;
                }//else
            }//try
            catch
            {
                //有错误,返回 false
                return false;
            }//catch
        }//Zip

        #endregion

        /// <summary>
        /// 打包下载文件
        /// </summary>
        /// <param name="files">string[] 文件列表</param>
        /// <returns>bool 下载是否成功</returns>
        public bool DownLoad(string[] files)
        {   //从配置文件中获取文件位置
            string filePlace = ConfigurationManager.AppSettings["FilePlace"];
            //获取报告数量
            int count=files.Length;
            //设置打包后的压缩文件名
            string fileName="Reports_Total_"+count+".rar";
            //定义Http相关信息
            HttpContext content = HttpContext.Current;

            for (int i = 0; i < files.Length; i++)
            {
                files[i] = filePlace+"//"+ files[i];
            }
            //定义http响应
            HttpResponse response = content.Response;
            //设置压缩后生成的压缩文件临时文件
            string strZipPath = content.Server.MapPath("~//temp//" + fileName);
            //设置被压缩文件的上级目录
            string strZipTopDirectoryPath = content.Server.MapPath("~");

            //压缩文件,压缩不成功,返回false
            if (!Zip(strZipPath,strZipTopDirectoryPath,6,null,files))
            {
                return false;
            } //if
           
            //设置Http响应
            response.Clear();
            response.AddHeader("content-disposition", "attachment;filename="+fileName);
            //将压缩的文件写入输入流
            response.WriteFile(strZipPath);
            //向客户端输出所有缓冲
            response.Flush();
            //下载完成后删除临时压缩文件
            if (File.Exists(strZipPath))
            {
                File.Delete(strZipPath);
            }
            //下载完成返回true
            return true;
        }

        #region 备用代码(数据文件过大时使用

        //由于上边代码对于大文件是一次读入,所以遇到大文件的时候是占用资源比较紧张。所以改为分段读取,每次读取64K数据:
        //string fileName = file.Replace(zipTopDirectory, "");
        //if (fileName.StartsWith(""))
        //  fileName = fileName.Substring(1);
        //ZipEntry entry = new ZipEntry(fileName);
        //entry.DateTime = DateTime.Now;
        //zipedStream.PutNextEntry(entry);
        //for (long j = 0; j < fs.Length; j += 65536)
        //{
        //  int byteLength = 65536;
        //  if ((fs.Length - j) < 65536)
        //  {
        //    byteLength = (int)(fs.Length - j);
        //  }

        //  byte[] buffer = new byte[byteLength];
        //  fs.Read(buffer, 0, byteLength);
        //  zipedStream.Write(buffer, 0, byteLength);
        //}
        //fs.Close();

        //MemoryStream ms = new MemoryStream();
        //byte[] buffer = null;

        //using (ZipFile file = ZipFile.Create(ms))
        //{
        //    file.BeginUpdate();
        //    //通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
        //    file.NameTransform = new MyNameTransfom();

        //    file.Add(Server.MapPath("~/images/1.jpg"));
        //    file.Add(Server.MapPath("~/images/2.jpg"));
        //    file.Add(Server.MapPath("~/images/3.jpg"));
           
        //    file.CommitUpdate();

        //    buffer = new byte[ms.Length];
        //    ms.Position = 0;
        //    ms.Read(buffer, 0, buffer.Length);
        //}

        //Response.AddHeader("content-disposition", "attachment;filename=Test.zip");
        //Response.BinaryWrite(buffer);
        //Response.Flush();
        //Response.End();

        ////专门写了一个NameTransfom
        //public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform {

        //    #region INameTransform 成员

        //    public string TransformDirectory(string name)
        //    {
        //        return null;
        //    }

        //    public string TransformFile(string name)
        //    {
        //        return Path.GetFileName(name);
        //    }

        //    #endregion
        //}

        #endregion

    }//FiledownloadControl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息