NetCore使用ZipFile 和ZipOutputStream

一、序言

  环境:NetCore 3.1

  项目类型:Web

二、使用ZipFile压缩本地文件

 

var filePath = Directory.GetCurrentDirectory() + $@"\ImgZip\{DateTime.Now:yyyy-MM-dd}";
            using (ZipFile zip = ZipFile.Create(@"D:\test.zip"))
            {
                zip.BeginUpdate();
                zip.SetComment("这是我的压缩包");
                zip.AddDirectory(filePath);  //添加一个文件夹(这个方法不会压缩文件夹里的文件)
                zip.Add(filePath + @"\118e0e67b82e43698b447f1d79a3f9a0.jpg");     //添加文件夹里的文件
                zip.CommitUpdate();
            }
            FileStream fileStream = System.IO.File.OpenRead(@"D:\test.zip");//打开压缩文件
            buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            fileStream.Close();
             return File(buffer , "application/zip", "118e0e67b82e43698b447f1d79a3f9a0.zip");

 

三、使用ZipOutputStream 压缩流文件

 

//获取远程文件,并读取为流文件
 string Url = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597509647515&di=3e0ca14b97aafdfd69fc60d3323eec06&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D3571592872%2C3353494284%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1200%26h%3D1290";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //超时时间 request.Timeout = 60000; //获取回写流 WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream outstream = new MemoryStream(); const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = stream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } byte[] result = null; //创建压缩流 using (MemoryStream ms = new MemoryStream()) { using ZipOutputStream zipStream = new ZipOutputStream(ms); //zipStream.Password = "123456";//设置压缩包密码 //ZipEntry 斜杠表示文件夹 为自动按照填写的路径生成多级目录 ZipEntry entry = new ZipEntry(@"文件夹1\文件夹2\118e0e67b82e43698b447f1d79a3f9a0.jpg") { DateTime = DateTime.Now,//创建时间 IsUnicodeText = true//解决中文乱码 }; zipStream.PutNextEntry(entry); zipStream.Write(outstream.ToArray(), 0, bytes.Length); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; zipStream.Finish(); zipStream.Close(); ms.Position = 0; //压缩后的数据被保存到了byte[]数组中。 result = ms.ToArray(); } return File(result, "application/zip", "118e0e67b82e43698b447f1d79a3f9a0.zip");

 

你可能感兴趣的:(NetCore使用ZipFile 和ZipOutputStream)