public static bool ZipTxtFile(string FileToZip, string ZipedFile, string ZipedFileName, int BlockSize) { try { FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read); if (File.Exists(ZipedFile)) { File.Delete(ZipedFile); } FileStream ZipFile = File.Create(ZipedFile); ZipOutputStream ZipStream = new ZipOutputStream(ZipFile); ZipEntry ZipEntry = new ZipEntry(ZipedFileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(6); byte[] buffer = new byte[BlockSize]; Int32 size = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, size); try { while (size < StreamToZip.Length) { int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, sizeRead); size += sizeRead; } } catch (Exception err) { SystemLog.logger(err.InnerException.Message); return false; } ZipStream.Finish(); ZipStream.Close(); StreamToZip.Close(); return true; } catch (Exception ex) { SystemLog.logger(ex.InnerException.Message); return false; } }
public static bool ZipFile(string filename) { bool isSuccess = false; string zipPath = "C:"; try { zipPath = System.Configuration.ConfigurationManager.AppSettings["ZipPath"]; FileStream fsTemp = File.OpenRead(filename); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename); string fileNameWithExtension = Path.GetFileName(filename); if (!zipPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { zipPath = zipPath + Path.DirectorySeparatorChar.ToString(); } isSuccess = FileUtility.ZipTxtFile(filename, zipPath + "request_" + fileNameWithoutExtension + ".zip", fileNameWithExtension, Convert.ToInt32(fsTemp.Length)); fsTemp.Close(); return isSuccess; } catch (Exception e) { isSuccess = false; SystemLog.logger(e.InnerException.Message); return isSuccess; } }
ICSharpCode.SharpZipLib.dll 下载地址:点击打开链接