C# 压缩和解压缩

来源:互联网 发布:国家电网 云计算 编辑:程序博客网 时间:2024/04/28 19:19

话不多说,直接上代码,最后有重要说明!!!哦对了,用的是ICSharpCode.SharpZipLib.Zip; 这个东西

压缩:

先声明个全局变量吧:

 //附件打包的变量 ZipOutputStream zos = null;
下面就是压缩的代码了:

  #region 压缩附件的相关        protected void btnFile_Click(object sender, EventArgs e)        {            dlZipDir();            dla.Style.Remove("display");        }        protected void dlZipDir()        {            MemoryStream ms = null;            Response.ContentType = "application/octet-stream";            strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');            Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");            ms = new MemoryStream();            zos = new ZipOutputStream(ms);            //加密            zos.Password = encrypt("1qaz@WSX");            addZipEntry();            zos.Finish();            zos.Close();            Response.Clear();            Response.BinaryWrite(ms.ToArray());            Response.End();               }        protected void addZipEntry()        {            DataTable dt = new DataTable();            dt = getAccessory();            string folder = Server.MapPath("Data\\Temp");            //FileInfo[] files = new FileInfo[dt.Rows.Count];            List<FileInfo> list = new List<FileInfo>();            GZipResult r = new GZipResult();            int num = 0;            if (dt.Rows.Count > 0)            {                for (int i = 0; i < dt.Rows.Count; i++)                {                    string path = dt.Rows[i]["Fjlj"].ToString();                    //string xh = dt.Rows[i]["Xh"].ToString();                    string servpath = ConfigurationManager.AppSettings["Fjlj"] + path;                    if (File.Exists(servpath))                    {                        FileInfo file = new FileInfo(servpath);                        FileStream fs = File.OpenRead(file.FullName);                        byte[] buffer = new byte[fs.Length];                        fs.Read(buffer, 0, buffer.Length);                        string _strFjlj = dt.Rows[i]["Fjlj"].ToString();                        string strEntryName = _strFjlj.Substring(_strFjlj.Length - 40);                        ZipEntry entry = new ZipEntry(strEntryName);                        zos.PutNextEntry(entry);                        zos.Write(buffer, 0, buffer.Length);                        fs.Close();                                           }                }                         }           }        /// <summary>        /// 获取所有附件的DataTable1        /// </summary>        /// <returns></returns>        private DataTable getAccessory()        {            DataTable dt = new DataTable();            BLL.Sys_Xxfj xxfjBll = new BLL.Sys_Xxfj();            dt = xxfjBll.getAccessory();            return dt;        }
还有MD5加密的方法

   #region "MD5加密"        /// <summary>        ///32位 MD5加密        /// </summary>        /// <param name="str">加密字符</param>        /// <returns></returns>        public static string encrypt(string str)        {            string cl = str;            string pwd = "";            MD5 md5 = MD5.Create();            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));            for (int i = 0; i < s.Length; i++)            {                pwd = pwd + s[i].ToString("X");            }            return pwd;        }        #endregion


下面是解压缩的“

 /// <summary>            /// 解压缩文件            /// </summary>            /// <param name="GzipFile">压缩包文件名</param>            /// <param name="targetPath">解压缩目标路径</param>                   public static void Decompress(string GzipFile, string targetPath)        {            //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";                string directoryName = targetPath;            if (!Directory.Exists(directoryName))            {                Directory.CreateDirectory(directoryName);//生成解压目录                }            string CurrentDirectory = directoryName;            byte[] data = new byte[2048];            int size = 2048;            ZipEntry theEntry = null;            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))            {                //解密                s.Password = encrypt("1qaz@WSX");                while ((theEntry = s.GetNextEntry()) != null)                {                    if (theEntry.IsDirectory)                    {// 该结点是目录                            if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);                    }                    else                    {                        if (theEntry.Name != String.Empty)                        {                            //  检查多级目录是否存在                              if (theEntry.Name.Contains("//"))                            {                                string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);                                if (!Directory.Exists(parentDirPath))                                {                                    Directory.CreateDirectory(CurrentDirectory + parentDirPath);                                }                            }                            //解压文件到指定的目录                                using (FileStream streamWriter = File.Create(CurrentDirectory + "\\" + theEntry.Name))                            {                                while (true)                                {                                    size = s.Read(data, 0, data.Length);                                    if (size <= 0) break;                                    streamWriter.Write(data, 0, size);                                }                                streamWriter.Close();                            }                        }                    }                }                s.Close();            }        }



最后的说明就是:这个压缩方法是将文件流到内存中,如果文件过大 有可能造成程序崩掉,反正我是崩掉了。。。

0 0