分享

c# 把文件压缩成Zip的压缩包格式

 上上谦obtxuzaf 2019-08-30

第一个参数 :要压缩的文件夹[也可以是文件夹下面的一个文件]

第二个参数:压缩后文件要保存的路径

private static void CreateZipFile(string filesPath, string zipFilePath)
        {
            if (!Directory.Exists(filesPath))
            {
                Console.WriteLine("Cannot find directory '{0}'", filesPath);
                return;
            }
            try
            {
                string[] filenames = Directory.GetFiles(filesPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9); // 压缩级别 0-9
                                   //s.Password = "123"; //Zip压缩文件密码
                    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 (Exception ex)
            {
                Console.WriteLine("Exception during processing {0}", ex);
            }
        }

----------------------------------------------------------------------------------------------

以上代码   直接拉过去    用法在下面

            string Afterpath = HttpContext.Current.Server.MapPath("~/YaSuo/");  //压缩后要保存的目录【当前程序的目录下面的文件夹】

            string Beforepath = HttpContext.Current.Server.MapPath("~/Downloader/");//要压缩的目录【当前程序的目录下面的文件夹】
            CreateZip(Beforepath, Afterpath + $"{replace(tablename)}ORM.zip");

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多