码迷,mamicode.com
首页 > Windows程序 > 详细

使用c#将多个文件放入文件夹中,并压缩下载

时间:2016-07-29 18:31:46      阅读:988      评论:0      收藏:0      [点我收藏+]

标签:

ZipClass.cs  这个是一个压缩文件的类,可直接复制使用,使用到的命名空间是

 

using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

 

请自行网上查找此压缩程序集下载使用

 

技术分享
 public class ZipClass
    {

        #region ZipFileDictory
        /// <summary>
        /// 递归压缩文件夹方法
        /// </summary>
        /// <param name="FolderToZip"></param>
        /// <param name="s"></param>
        /// <param name="ParentFolderName"></param>
        private bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
        {
            bool res = true;
            string[] folders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                //创建当前文件夹
                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));  //加上 “/” 才会当成是文件夹创建
                s.PutNextEntry(entry);
                s.Flush();
                //先压缩文件,再递归压缩文件夹 
                filenames = Directory.GetFiles(FolderToZip);
                foreach (string file in filenames)
                {
                    //打开压缩文件
                    fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                    entry = null;
                GC.Collect();
                GC.Collect(1);
            }
            folders = Directory.GetDirectories(FolderToZip);
            foreach (string folder in folders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                    return false;
            }
            return res;
        }

        #endregion


        #region ZipFileDictory

        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
        /// <returns></returns>
        private string ZipFileDictory(string FolderToZip, string ZipedFile, string Password)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
                return "错误";
            ZipOutputStream s = new ZipOutputStream(File.Create(@""+FolderToZip+".zip"));
            s.SetLevel(6);
            if (!string.IsNullOrEmpty(Password.Trim()))
                s.Password = Password.Trim();
            res = ZipFileDictory(FolderToZip, s, "");
            s.Finish();
            s.Close();
            if (res)
            {
                return ZipedFile;
            }
            else
            {
                return null;
            }

        }

        #endregion

        #region ZipFile

        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="FileToZip">要进行压缩的文件名</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名</param>
        /// <returns></returns>
        private string ZipFile(string FileToZip, string ZipedFile, string Password)
        {
            //如果文件没有找到,则报错
            if (!File.Exists(FileToZip))
                throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            //FileStream fs = null;
            FileStream ZipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry ZipEntry = null;
            string res;
            try
            {
                ZipFile = File.OpenRead(FileToZip);
                byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 0, buffer.Length);
                ZipFile.Close();
                ZipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(ZipFile);
                if (!string.IsNullOrEmpty(Password.Trim()))
                    ZipStream.Password = Password.Trim();
                ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(6);
                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch
            {
                res = "错误";
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            return "成功";
        }

        #endregion

        #region Zip

        /// <summary>
        /// 压缩文件 和 文件夹
        /// </summary>
        /// <param name="FileToZip">待压缩的文件或文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后生,全路成的压缩文件名径格式</param>
        /// <param name="Password">压缩密码</param>
        /// <returns></returns>
        public string Zip(string FileToZip, string ZipedFile, string Password)
        {
            if (Directory.Exists(FileToZip))
            {
                return ZipFileDictory(FileToZip, ZipedFile, Password);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, ZipedFile, Password);
            }
            else
            {
                return "失败";
            }
        }

        /// <summary>
        /// 压缩文件 和 文件夹
        /// </summary>
        /// <param name="FileToZip">待压缩的文件或文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param>
        /// <returns></returns>
        public string Zip(string FileToZip, string ZipedFile)
        {
            return Zip(FileToZip, ZipedFile, "");
        }

        #endregion

    }
View Code

 

类使用方法:

 

技术分享
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Firstload();

                ResponseFile();

            }
        }
View Code
技术分享
/// <summary>
        /// 输出文件流
        /// </summary>
        protected void ResponseFile()
        {
            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=CurriculumDocument.zip");
            string filename = Webpath+".zip";
            Response.TransmitFile(filename);

            //输出文件流之后删除服务器中文件夹
            if (Directory.Exists(Webpath))
            {
                Directory.Delete(Webpath, true); //true为递归删除子文件内容
            }
        }

        public string FileName = "";
        public string Webpath = "";
        /// <summary>
        /// 页面第一次加载时开始获取文件压缩
        /// </summary>
        /// <returns></returns>
        private string Firstload()
        {
            //当前目录下新建文件夹
            Webpath = Server.MapPath("./CurriculumFiles/下载文件/" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Second + DateTime.Now.Millisecond);
         
            //文件名称
            FileName = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Second + DateTime.Now.Millisecond;

            //判断文件夹是否存在
            if (Directory.Exists(Webpath))
            {
                //true为递归删除子文件内容
                Directory.Delete(Webpath, true);
                Directory.CreateDirectory(Webpath);
            }
            else if (!Directory.Exists(Webpath))
            {
                Directory.CreateDirectory(Webpath);
            }

            //将要下载的文件copy到新的文件夹中
            List<string> DocumentNames_List = GetDocumentNames(ClassID);
            for (int i = 0; i < DocumentNames_List.Count;i++)
            {
                //获取服务器中CurriculumFiles目录下的文件及其路径
                string DocumentFileName=Server.MapPath("./CurriculumFiles/" + DocumentNames_List[i] + "");
                //判断文件是否存在
                if (File.Exists(DocumentFileName))
                {
                    File.Copy(DocumentFileName, Webpath + "\\" + "" + DocumentNames_List[i] + "", true);
                }
            }
            //压缩文件
            ZipClass zipClass = new ZipClass();
            return zipClass.Zip(Webpath, FileName);
        }
View Code

 

使用c#将多个文件放入文件夹中,并压缩下载

标签:

原文地址:http://www.cnblogs.com/ly77461/p/5719102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!