NetCore使用ZipFile 和ZipOutputStream

1、序言

  環境:NetCore 3.1數組

  項目類型:Webapp

2、使用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");

 

3、使用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");

相關文章
相關標籤/搜索