public SetLevel ( int level ) : void | ||
level | int | The new compression level (1 to 9). |
return | void |
public static void ZipFiles(string InputFolderPath, string outputPathAndFile, string password) { string outPath = outputPathAndFile; ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); int TrimLength = 0; if (Directory.GetParent(InputFolderPath) != null) { TrimLength = (Directory.GetParent(InputFolderPath)).ToString().Length; TrimLength += 1; //remove '\' } string DirPath = outPath.Remove(outPath.LastIndexOf(@"\")); if (!Directory.Exists(DirPath)) Directory.CreateDirectory(DirPath); DirectoryInfo dinf = new DirectoryInfo(InputFolderPath); if (dinf.Exists) { if (!string.IsNullOrEmpty(password)) oZipStream.Password = password; oZipStream.SetLevel(9); // maximum compression ArrayList ar = GenerateFileList(InputFolderPath); // generate file list foreach (object t in ar) { string Fil = t.ToString(); ZipFile(TrimLength, oZipStream, Fil); } } else { FileInfo finf = new FileInfo(InputFolderPath); if (!string.IsNullOrEmpty(password)) oZipStream.Password = password; oZipStream.SetLevel(9); // maximum compression ZipFile(TrimLength, oZipStream, finf.FullName); } oZipStream.Finish(); oZipStream.Close(); }
public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize) { //如果文件没有找到,则报错 if (!System.IO.File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd"); } System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile); ZipOutputStream ZipStream = new ZipOutputStream(ZipFile); ZipEntry ZipEntry = new ZipEntry("ZippedFile"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(CompressionLevel); byte[] buffer = new byte[BlockSize]; System.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 (System.Exception ex) { throw ex; } ZipStream.Finish(); ZipStream.Close(); StreamToZip.Close(); }
public static string PackToBase64(string text) { byte[] buffer; MemoryStream ms = new MemoryStream(); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms)) { zipOutputStream.SetLevel(9); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin"); zipOutputStream.PutNextEntry(zipEntry); byte[] bytes = System.Text.Encoding.Unicode.GetBytes(text.ToCharArray()); zipOutputStream.Write(bytes, 0, bytes.Length); zipOutputStream.Flush(); zipOutputStream.Finish(); buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, Convert.ToInt32(ms.Length)); }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ... return(ToBase64(buffer)); }
public override void ExecuteResult(ControllerContext context) { string fileName = Path.GetTempFileName(); var response = context.HttpContext.Response; using (var zipOutputStream = new ZipOutputStream(new FileStream(fileName, FileMode.OpenOrCreate))) { zipOutputStream.SetLevel(0); foreach (var photo in Photos) { //FileInfo fileInfo = new FileInfo(photo.MediaFilePath); ZipEntry entry = new ZipEntry(Tag.Name + @"\" + photo.Id + ".jpg"); zipOutputStream.PutNextEntry(entry); using (FileStream fs = System.IO.File.OpenRead(photo.MediaFilePath)) { byte[] buff = new byte[1024]; int n = 0; while ((n = fs.Read(buff, 0, buff.Length)) > 0) zipOutputStream.Write(buff, 0, n); } } zipOutputStream.Finish(); } System.IO.FileInfo file = new System.IO.FileInfo(fileName); response.Clear(); response.AddHeader("Content-Disposition", "attachment; filename=" + "Photos.zip"); response.AddHeader("Content-Length", file.Length.ToString()); response.ContentType = "application/octet-stream"; response.WriteFile(file.FullName); response.End(); System.IO.File.Delete(fileName); }
/// <summary> /// Compress an string using ZIP /// </summary> /// <param name="xml"></param> /// <returns></returns> public static byte[] CompressContent(string contentToZip) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] buff = encoding.GetBytes(contentToZip); try { using (MemoryStream stream = new MemoryStream()) { using (ZipOutputStream zipout = new ZipOutputStream(stream)) { zipout.SetLevel(9); ZipEntry entry = new ZipEntry("zipfile.zip"); entry.DateTime = DateTime.Now; zipout.PutNextEntry(entry); zipout.Write(buff, 0, buff.Length); zipout.Finish(); byte[] outputbyte = new byte[(int)stream.Length]; stream.Position = 0; stream.Read(outputbyte, 0, (int)stream.Length); return outputbyte; } } } catch (Exception ex) { ex.Message.ToString(); return null; } }
public override Stream GetWriteStream(UploadedFile file) { file.ServerLocation = Path.Combine(HttpContext.Current.Server.MapPath(_location), Path.GetFileNameWithoutExtension(GetValidFileName(file.ClientName)) + ".zip"); Directory.CreateDirectory(Path.GetDirectoryName(file.ServerLocation)); FileStream fileS = null; ZipOutputStream zipS = null; try { fileS = File.OpenWrite(file.ServerLocation); zipS = new ZipOutputStream(fileS); zipS.SetLevel(5); zipS.PutNextEntry(new ZipEntry(file.ClientName)); return zipS; } catch { if (zipS != null) zipS.Dispose(); if (fileS != null) fileS.Dispose(); throw; } }
public void Save(string extPath) { // https://forums.xamarin.com/discussion/7499/android-content-getexternalfilesdir-is-it-available Java.IO.File sd = Android.OS.Environment.ExternalStorageDirectory; //FileStream fsOut = File.Create(sd.AbsolutePath + "/Android/data/com.FSoft.are_u_ok_/files/MoodData.zip"); FileStream fsOut = File.Create(extPath + "/MoodData.zip"); //https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples ZipOutputStream zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel (3); //0-9, 9 being the highest level of compression zipStream.Password = "******"; // optional. Null is the same as not setting. Required if using AES. ZipEntry newEntry = new ZipEntry ("Mood.csv"); newEntry.IsCrypted = true; zipStream.PutNextEntry (newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[ ] buffer = new byte[4096]; string filename = extPath + "/MoodData.csv"; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry (); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close (); }
/// <summary> /// Método que faz o zip de arquivos encontrados no diretório <strPathDirectory> /// </summary> /// <param name="strPath"></param> public static void ZipFiles(String strPathDirectory, String strZipName) { try { using (ZipOutputStream ZipOut = new ZipOutputStream(File.Create(strPathDirectory + "\\" + strZipName + ".zip"))) { string[] OLfiles = Directory.GetFiles(strPathDirectory); Console.WriteLine(OLfiles.Length); ZipOut.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string filename in OLfiles) { ZipEntry entry = new ZipEntry(Path.GetFileName(filename)); ZipOut.PutNextEntry(entry); using (FileStream fs = File.OpenRead(filename)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); ZipOut.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } ZipOut.Finish(); ZipOut.Close(); } } catch (System.Exception ex) { System.Console.Error.WriteLine("exception: " + ex); //TODO colocar log } }
public void PackageFiles(IEnumerable<ZipFileEntry> filesToZip) { using (var zipStream = new ZipOutputStream(File.Create(ZipFilePath))) { if (!string.IsNullOrEmpty(Password)) { zipStream.Password = Password; } zipStream.SetLevel(9); // 9 -> "highest compression" foreach (var fileEntry in filesToZip) { var zipEntry = new ZipEntry(fileEntry.FilePathInsideZip); var fileInfo = new FileInfo(fileEntry.AbsoluteFilePath); zipEntry.DateTime = fileInfo.LastWriteTime; zipEntry.Size = fileInfo.Length; zipStream.PutNextEntry(zipEntry); // Zip the file in buffered chunks var buffer = new byte[4096]; using (var streamReader = File.OpenRead(fileEntry.AbsoluteFilePath)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.Finish(); zipStream.Close(); } }
/// <summary> /// 将文件或目录压缩。 /// </summary> /// <param name="paths">路径集合。</param> /// <returns>压缩后数据</returns> public static byte[] Zip(string[] paths) { byte[] data = null; if (paths != null && paths.Length > 0) { using (MemoryStream ms = new MemoryStream()) { //压缩数据保存到临时文件。 using (ZipOutputStream zipStream = new ZipOutputStream(ms)) { zipStream.SetLevel(9); for (int i = 0; i < paths.Length; i++) { if (File.Exists(paths[i])) { ZipFileData(zipStream, paths[i], null, null); } else if (Directory.Exists(paths[i])) { ZipFolderData(zipStream, paths[i], string.Empty); } } zipStream.IsStreamOwner = true; zipStream.Close(); } data = ms.ToArray(); } } return data; }
/// <summary> /// Zips the specified source (File or Directory). /// </summary> public void Zip() { Common.ValidateOverwrite(this.overwriteTarget, this.target); this.Log(String.Format("Zipping: [{0}] -> [{1}].", this.source, this.target), LogLevel.Minimal); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(this.target))) { zipStream.SetLevel((int)zipLevel); if (!String.IsNullOrEmpty(this.password)) zipStream.Password = this.password; DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(this.source)); List<string> fileList = Common.GetFileList(this.source, this.fileFilter, this.recursive); if (fileList.Count == 0) this.Log(String.Format("No files found matching the filter criteria."), LogLevel.Verbose); foreach (string filePath in fileList) { this.zipFile(zipStream, dir, new FileInfo(filePath)); } zipStream.IsStreamOwner = true; zipStream.Close(); } this.Log(String.Format("Successfully Zipped: [{0}] -> [{1}].", this.source, this.target), LogLevel.Minimal); Common.RemoveFile(this.removeSource, this.source); }
/// <summary> /// Compresses an array of bytes and stores the result in a new array of bytes. /// </summary> /// <param name="uncompressed">The uncompressed buffer.</param> /// <param name="compressed">An array of bytes where the compressed input will be stored.</param> /// <remarks> /// The compressed input is passed back to the calling method as an <b>out</b> /// parameter. That means that the calling method doesn't need to initialize the /// compressed buffer. /// </remarks> /// <exception cref="ArgumentNullException"> /// Thrown if the uncompressed input buffer is empty or null. /// </exception> /// <exception cref="CWZipException"> /// Thrown if a problem is encountered during the compression process. /// </exception> public static void CompressBuffer(byte[] uncompressed, out byte[] compressed) { if ((uncompressed == null) || (uncompressed.Length == 0)) { throw new ArgumentNullException("uncompressed", "The uncompressed input buffer cannot be null or empty."); } MemoryStream ms = null; compressed = null; try { ms = new MemoryStream(); ZipOutputStream zip = new ZipOutputStream(ms); zip.SetLevel(compressionLevel); ZipEntry entry = new ZipEntry("1"); zip.PutNextEntry(entry); zip.Write(uncompressed, 0, uncompressed.Length); zip.Finish(); ms.Position = 0; compressed = ms.ToArray(); ms.Close(); } catch (Exception e) { if (ms != null) { ms.Close(); } throw new CWZipException(e.Message); } finally { ms = null; GC.Collect(); } }
public override Stream GetOutputStream(UploadedFile file) { FileStream fileS = null; ZipOutputStream zipS = null; try { string outputPath = GetZipPath(file); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); fileS = File.OpenWrite(outputPath); zipS = new ZipOutputStream(fileS); zipS.SetLevel(5); zipS.PutNextEntry(new ZipEntry(file.ClientName)); file.LocationInfo[FileNameKey] = outputPath; return zipS; } catch { if (fileS != null) fileS.Close(); if (zipS != null) zipS.Close(); return null; } }
public void zip(string to, string[] files) { using (ZipOutputStream s = new ZipOutputStream(File.Create(to))) { s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string file in files) { ZipEntry entry = new ZipEntry(Path.GetFileName(file)) { 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(); } }
private void CompressFilesToOneZipFile(ICollection<string> inputPaths, string zipFilePath) { Log.LogMessage(MessageImportance.Normal, "Zipping " + inputPaths.Count + " files to zip file " + zipFilePath); using (var fsOut = File.Create(zipFilePath)) // Overwrites previous file { using (var zipStream = new ZipOutputStream(fsOut)) { foreach (var inputPath in inputPaths) { zipStream.SetLevel(9); // Highest level of compression var inputFileInfo = new FileInfo(inputPath); var newEntry = new ZipEntry(inputFileInfo.Name) { DateTime = inputFileInfo.CreationTime }; zipStream.PutNextEntry(newEntry); var buffer = new byte[4096]; using (var streamReader = File.OpenRead(inputPath)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.IsStreamOwner = true; zipStream.Close(); } } }
/// <summary> /// Zips the files in the specifed directory and outputs the zip file to the specified location. /// </summary> /// <param name="zipFilePath">The full path to the output zip file.</param> /// <returns>The total number of files added to the zip file.</returns> public int ZipToFile(string zipFilePath) { int total = 0; if (Directory.Exists(DirectoryPath)) { if (!Directory.Exists(Path.GetDirectoryName(zipFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath)); } // Create the zip file //Crc32 crc = new Crc32(); ZipOutputStream zipFile = new ZipOutputStream(File.Create(zipFilePath)); zipFile.UseZip64 = UseZip64.Off; zipFile.SetLevel(9); total += ZipFromPath(zipFile, DirectoryPath); // Close the writer zipFile.Finish(); zipFile.Close(); } return total; }
public void Zip(string outPathname, IList<ZipItem> contents) { var outputStream = File.Create(outPathname); var zipStream = new ZipOutputStream(outputStream); zipStream.SetLevel(3); foreach (var item in contents) { if (item.IsDirectory) { var files = Directory.EnumerateFiles(item.FilePath); foreach (var file in files) { AppendFile(zipStream, item.FolderInZip, file); } } else { AppendFile(zipStream, item.FolderInZip, item.FilePath); } } zipStream.IsStreamOwner = true; zipStream.Close(); }
private static ZipOutputStream OpenZipStream(Purl path) { Stream stream = path.CreateFile(); ZipOutputStream zip = new ZipOutputStream(stream); zip.SetLevel(5); return zip; }
public static void Zip(string strFile, string strZipFile) { Crc32 crc1 = new Crc32(); ZipOutputStream stream1 = new ZipOutputStream(File.Create(strZipFile)); try { stream1.SetLevel(6); FileStream stream2 = File.OpenRead(strFile); byte[] buffer1 = new byte[stream2.Length]; stream2.Read(buffer1, 0, buffer1.Length); ZipEntry entry1 = new ZipEntry(strFile.Split(new char[] { '\\' })[strFile.Split(new char[] { '\\' }).Length - 1]); entry1.DateTime = DateTime.Now; entry1.Size = stream2.Length; stream2.Close(); crc1.Reset(); crc1.Update(buffer1); entry1.Crc = crc1.Value; stream1.PutNextEntry(entry1); stream1.Write(buffer1, 0, buffer1.Length); } catch (Exception exception1) { throw exception1; } finally { stream1.Finish(); stream1.Close(); stream1 = null; crc1 = null; } }
public ZipFileBuilder(Stream outStream) { zipStream = new ZipOutputStream(outStream); zipStream.SetLevel(9); //best compression factory = new ZipEntryFactory(DateTime.Now); }
public static void CreateZipFile(string[] filenames, string outputFile) { // Zip up the files - From SharpZipLib Demo Code using (ZipOutputStream s = new ZipOutputStream(File.Create(outputFile))) { s.SetLevel(9); // 0-9, 9 being the highest level of compression 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(); } }
public FileResult DownloadAllFiles() { var context = System.Web.HttpContext.Current; var folderPath = context.Server.MapPath("~/UploadedFiles/"); var baseOutputStream = new MemoryStream(); ZipOutputStream zipOutput = new ZipOutputStream(baseOutputStream) {IsStreamOwner = false}; /* * Higher compression level will cause higher usage of reources * If not necessary do not use highest level 9 */ zipOutput.SetLevel(4); SharpZipLibHelper.ZipFolder(folderPath, zipOutput); zipOutput.Finish(); zipOutput.Close(); /* Set position to 0 so that cient start reading of the stream from the begining */ baseOutputStream.Position = 0; /* Set custom headers to force browser to download the file instad of trying to open it */ return new FileStreamResult(baseOutputStream, "application/x-zip-compressed") { FileDownloadName = "eResult.zip" }; }
private static void CreateToMemoryStream(IEnumerable<Tuple<string, Stream>> entries, string zipName) { MemoryStream outputMemStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression foreach (var entry in entries) { ZipEntry newEntry = new ZipEntry(entry.Item1); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); StreamUtils.Copy(entry.Item2, zipStream, new byte[4096]); zipStream.CloseEntry(); } zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. outputMemStream.Position = 0; File.WriteAllBytes(zipName, outputMemStream.ToArray()); //// Alternative outputs: //// ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory. //byte[] byteArrayOut = outputMemStream.ToArray(); //// GetBuffer returns a raw buffer raw and so you need to account for the true length yourself. //byte[] byteArrayOut = outputMemStream.GetBuffer(); //long len = outputMemStream.Length; }
public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password) { ArrayList ar = GenerateFileList(inputFolderPath); // generate file list int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length; // find number of chars to remove // from orginal file path TrimLength += 1; //remove '\' FileStream ostream; byte[] obuffer; string outPath = outputPathAndFile; ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream if (password != null && password != String.Empty) oZipStream.Password = password; oZipStream.SetLevel(9); // maximum compression ZipEntry oZipEntry; foreach (string Fil in ar) // for each file, generate a zipentry { oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipStream.PutNextEntry(oZipEntry); if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); } } oZipStream.Finish(); oZipStream.Close(); oZipStream.Dispose(); }
/// <summary> /// Creates a zip file out of specified input files /// </summary> /// <param name="files">input files</param> /// <param name="zipFileName">output zip file</param> /// <exception cref="System.ArgumentException">No file must exist with specified zip file name.</exception> public void Zip(FileInfo[] files, string zipFileName) { if (File.Exists(zipFileName)) throw new ArgumentException("Es existiert bereits eine Datei unter diesem Namen.", "zipFileName"); using (FileStream fs = new FileStream(zipFileName, FileMode.CreateNew)) { using (ZipOutputStream stream = new ZipOutputStream(fs)) { stream.SetLevel(9); foreach (FileInfo file in files) { ZipEntry entry = new ZipEntry(file.Name) { DateTime = DateTime.Now }; using (FileStream entryFs = file.OpenRead()) { byte[] buffer = new byte[entryFs.Length]; entryFs.Read(buffer, 0, buffer.Length); entry.Size = entryFs.Length; stream.PutNextEntry(entry); stream.Write(buffer, 0, buffer.Length); } } stream.Finish(); } } }
// See this link for details on zipping using SharpZipLib: https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#wiki-anchorCreate public void Write(Cookbookology.Domain.Cookbook cookbook, Stream outputStream) { if (cookbook == null) throw new ArgumentNullException("cookbook"); if (outputStream == null) throw new ArgumentNullException("outputStream"); var converter = new MyCookbookConverter(); var mcb = converter.ConvertFromCommon(cookbook); var ms = new MemoryStream(); var s = new XmlSerializer(typeof(Cookbook)); s.Serialize(ms, mcb); ms.Position = 0; // reset to the start so that we can write the stream // Add the cookbook as a single compressed file in a Zip using (var zipStream = new ZipOutputStream(outputStream)) { zipStream.SetLevel(3); // compression zipStream.UseZip64 = UseZip64.Off; // not compatible with all utilities and OS (WinXp, WinZip8, Java, etc.) var entry = new ZipEntry(mcbFileName); entry.DateTime = DateTime.Now; zipStream.PutNextEntry(entry); StreamUtils.Copy(ms, zipStream, new byte[4096]); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; // Don't close the outputStream (parameter) zipStream.Close(); } }
public static string PackToBase64(byte[] data) { byte[] buffer; MemoryStream ms = new MemoryStream(); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms)) { zipOutputStream.SetLevel(9); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin"); zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.Write(data, 0, data.Length); zipOutputStream.Flush(); zipOutputStream.Finish(); buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, Convert.ToInt32(ms.Length)); }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ... return(ToBase64(buffer)); }
public void CreateZipFile(string[] straFilenames, string strOutputFilename) { Crc32 crc = new Crc32(); ZipOutputStream zos = new ZipOutputStream(File.Create(strOutputFilename)); zos.SetLevel(m_nCompressionLevel); foreach (string strFileName in straFilenames) { FileStream fs = File.OpenRead(strFileName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(GetFileNameWithoutDrive(strFileName)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zos.PutNextEntry(entry); zos.Write(buffer, 0, buffer.Length); } zos.Finish(); zos.Close(); }
/// <summary> /// 压缩文件夹 /// </summary> /// <param name="dirToZip"></param> /// <param name="zipedFileName"></param> /// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param> public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9) { if (Path.GetExtension(zipedFileName) != ".zip") { zipedFileName = zipedFileName + ".zip"; } using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName))) { zipoutputstream.SetLevel(compressionLevel); var crc = new Crc32(); var fileList = GetAllFies(dirToZip); foreach (DictionaryEntry item in fileList) { var fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); // ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1)); var entry = new ZipEntry(Path.GetFileName(item.Key.ToString())) { DateTime = (DateTime) item.Value, Size = fs.Length }; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipoutputstream.PutNextEntry(entry); zipoutputstream.Write(buffer, 0, buffer.Length); } } }
public static void CreateFromDirectory(string[] sourceFileNames, string destinationArchiveFileName) { using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationArchiveFileName))) { byte[] buffer = new byte[BufferSize]; zipStream.SetLevel(9); foreach (string file in sourceFileNames) { var entryName = Path.GetFileName(file); var fileInfo = new FileInfo(file); ZipEntry entry = new ZipEntry(entryName); entry.DateTime = fileInfo.LastWriteTime; zipStream.PutNextEntry(entry); using (FileStream fileStream = File.OpenRead(file)) { while (true) { int size = fileStream.Read(buffer, 0, buffer.Length); if (size <= 0) break; zipStream.Write(buffer, 0, size); } } } zipStream.Finish(); zipStream.Close(); } }
public static void CompressFiles(IEnumerable<ISong> files, string destinationPath) { if (log.IsDebugEnabled) { log.Debug("Starting creation of zip file : " + destinationPath); } using (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileStream(destinationPath, FileMode.OpenOrCreate))) { zipOutputStream.SetLevel(0); foreach (ISong song in files) { FileInfo fileInfo = new FileInfo(song.MediaFilePath); ZipEntry entry = new ZipEntry(song.Artist.Name + "\\" + song.Album.Name + "\\" + song.Title + fileInfo.Extension); zipOutputStream.PutNextEntry(entry); FileStream fs = File.OpenRead(song.MediaFilePath); byte[] buff = new byte[1024]; int n = 0; while ((n = fs.Read(buff, 0, buff.Length)) > 0) { zipOutputStream.Write(buff, 0, n); } fs.Close(); } zipOutputStream.Finish(); } if (log.IsDebugEnabled) { log.Debug("Zip file created : " + destinationPath); } }
private void Page_Load(object sender, System.EventArgs e) { System.DateTime dateTime = System.DateTime.Now; string s1 = "Message_Backup_\uFFFD" + dateTime.ToString("ddMMyy_HHmmss\uFFFD") + ".zip\uFFFD"; System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(memoryStream); ActiveUp.Net.Mail.Mailbox mailbox = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(Request.QueryString["b\uFFFD"]); char[] chArr = new char[] { ',' }; string[] sArr = Request.QueryString["m\uFFFD"].Split(chArr); for (int i = 0; i < sArr.Length; i++) { string s2 = sArr[i]; byte[] bArr = mailbox.Fetch.Message(System.Convert.ToInt32(s2)); ActiveUp.Net.Mail.Header header = ActiveUp.Net.Mail.Parser.ParseHeader(bArr); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(header.Subject + ".eml\uFFFD"); zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.SetLevel(9); zipOutputStream.Write(bArr, 0, bArr.Length); zipOutputStream.CloseEntry(); } zipOutputStream.Finish(); Response.AddHeader("Content-Disposition\uFFFD", "attachment; filename=\uFFFD" + s1); Response.ContentType = "application/zip\uFFFD"; Response.BinaryWrite(memoryStream.GetBuffer()); zipOutputStream.Close(); }
public static string CreateZIPFile(string path, int M, string strsuff) { try { Crc32 crc = new Crc32();//未压缩的 ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipout = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(path + ".zip")); //ICSharpCode.SharpZipLib.GZip.GZipOutputStream zipout = new GZipOutputStream(System.IO.File.Create(path+ ".zip")); System.IO.FileStream fs = System.IO.File.OpenRead(path + strsuff); long pai = 1024 * 1024 * M;//每M兆写一次 long forint = fs.Length / pai + 1; byte[] buffer = null; zipout.SetLevel(7); ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(path + strsuff)); entry.Size = fs.Length; entry.DateTime = DateTime.Now; zipout.PutNextEntry(entry); //zipout. for (long i = 1; i <= forint; i++) { if (pai * i < fs.Length) { buffer = new byte[pai]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } else { if (fs.Length < pai) { buffer = new byte[fs.Length]; } else { buffer = new byte[fs.Length - pai * (i - 1)]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } } fs.Read(buffer, 0, buffer.Length); crc.Reset(); crc.Update(buffer); zipout.Write(buffer, 0, buffer.Length); zipout.Flush(); } fs.Close(); zipout.Finish(); zipout.Close(); System.IO.File.Delete(path + strsuff); // File.Create(path.Replace(".doc","") + ".zip",buffer.Length); return(path + ".zip"); } catch (Exception ex) { string str = ex.Message; return(path); } }
public static ZipFileSystem CreateZipFile(IFile zipFile, IEnumerable <IFile> files, Func <IFile, string> fileToFullPath, FileSystemOptions options) { var compressionLevel = 9; var zipCompressionLevel = options.Variables["ZipCompressionLevel"]; if (zipCompressionLevel != null) { compressionLevel = Convert.ToInt32(zipCompressionLevel); if (compressionLevel < 0) { compressionLevel = 0; } else if (compressionLevel > 9) { compressionLevel = 9; } } var password = options.Variables["ZipPassword"]; using (var zipOutputStream = new ZLib.ZipOutputStream(zipFile.GetContent().GetOutputStream())) { zipOutputStream.SetLevel(compressionLevel); zipOutputStream.IsStreamOwner = true; zipOutputStream.UseZip64 = ZLib.UseZip64.Dynamic; zipOutputStream.Password = password; if (files != null) { foreach (var file in files) { var entryName = fileToFullPath(file); entryName = ZLib.ZipEntry.CleanName(entryName); var entry = new ZLib.ZipEntry(entryName); using (var stream = file.GetContent().GetInputStream(FileMode.Open, FileShare.Read)) { if (stream.Length > 0) { entry.Size = stream.Length; } zipOutputStream.PutNextEntry(entry); stream.CopyTo(zipOutputStream); } zipOutputStream.CloseEntry(); } } } return(new ZipFileSystem(zipFile, options)); }
/// <summary> /// 压缩多个文件/文件夹 /// </summary> /// <param name="comment">注释信息</param> /// <param name="password">压缩密码</param> /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param> /// <param name="filePaths">压缩文件路径</param> /// <returns></returns> private MemoryStream CreateZip(string comment, string password, int compressionLevel, params string[] filePaths) { MemoryStream memoryStream = new MemoryStream(); using (SharpZipLib.ZipOutputStream zipStream = new SharpZipLib.ZipOutputStream(memoryStream)) { if (!string.IsNullOrWhiteSpace(password)) { zipStream.Password = password;//设置密码 } if (!string.IsNullOrWhiteSpace(comment)) { zipStream.SetComment(comment);//添加注释 } //设置压缩级别 zipStream.SetLevel(compressionLevel); foreach (string item in filePaths)//从字典取文件添加到压缩文件 { //如果不是文件直接跳过不打包 if (!File.Exists(item)) { continue; } FileInfo fileInfo = new FileInfo(item); using (FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { SharpZipLib.ZipEntry zipEntry = new SharpZipLib.ZipEntry(Path.GetFileName(item)); zipEntry.DateTime = fileInfo.LastWriteTime; zipEntry.Size = fileStream.Length; zipStream.PutNextEntry(zipEntry); int readLength = 0; byte[] buffer = new byte[bufferSize]; do { readLength = fileStream.Read(buffer, 0, bufferSize); zipStream.Write(buffer, 0, readLength); }while (readLength == bufferSize); } } } return(memoryStream); }
/// <summary> /// 压缩文件(Zip) /// </summary> /// <param name="filesPath">待压缩文件目录</param> /// <param name="zipFilePath">压缩文件输出目录</param> /// <returns></returns> public static ZipInfo CreateZipFile(string filesPath, string zipFilePath) { if (!System.IO.Directory.Exists(filesPath)) { return(new ZipInfo { Success = false, InfoMessage = "没有找到文件" }); } try { string[] filenames = System.IO.Directory.GetFiles(filesPath); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); // 压缩级别 0-9 //s.Password = "******"; //Zip压缩文件密码 byte[] buffer = new byte[4096]; //缓冲区大小 foreach (string file in filenames) { ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.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(); } return(new ZipInfo { Success = true, InfoMessage = "压缩成功" }); } catch (Exception ex) { return(new ZipInfo { Success = false, InfoMessage = ex.Message }); } }
public static Boolean ZipFile(String filePath, String zipFile) { if (!File.Exists(filePath)) { Debug.WriteLine("Cannot find file '{0}'", filePath); return(false); } try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFile))) { zipStream.SetLevel(9); //0~9 byte[] buffer = new byte[4096]; ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(filePath)); entry.DateTime = DateTime.Now; zipStream.PutNextEntry(entry); using (FileStream fs = File.OpenRead(filePath)) { int sourceBytes = 0; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } zipStream.Finish(); zipStream.Close(); zipStream.Dispose(); } if (File.Exists(zipFile)) { return(true); } } catch (Exception ex) { Debug.WriteLine("Exception during processing {0}", ex); } return(false); }
private String CompressionDossier(String pFichier) { try { if (Directory.Exists(pFichier) == true) { //System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(); using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(String.Format("{0}.zip", pFichier)))) { s.SetLevel(9); var buffer = new byte[4096]; var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(pFichier) { DateTime = DateTime.Now }; s.PutNextEntry(entry); using (StreamReader fs = new StreamReader(pFichier)) { int sourceBytes; do { sourceBytes = fs.Read(); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } s.Finish(); s.Close(); s.Dispose(); pFichier = string.Format("{0}.zip", pFichier); } //} } return(pFichier); } catch (Exception ex) { throw ex; } }
public async Task <Stream> CompressFile(Dictionary <string, Stream> fileDic, string password) { var result = new MemoryStream(); var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(result); zipStream.Password = string.Empty; zipStream.SetLevel(9); //0-9, 9 being the highest level of compression foreach (var data in fileDic) { var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(data.Key) { DateTime = DateTime.Now, IsUnicodeText = true }; zipStream.PutNextEntry(newEntry); var length = data.Value.Length < 1024 ? 1024 : data.Value.Length; ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(data.Value, zipStream, new byte[length]); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. } zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. result.Position = 0; return(result); }
}// ZipFile /// <summary> /// Zip multiple files(fileNames) in directory(directory) to (flowName).zip. /// </summary> /// <param name="directory"></param> /// <param name="fileNames"></param> /// <param name="reportName"></param> public static void PackFilesIntoOne(string directory, string[] fileNames, string outputFilename) { if (directory == null) { throw new ArgumentNullException("directory"); } if (fileNames == null) { throw new ArgumentNullException("fileNames"); } if (outputFilename == null) { throw new ArgumentNullException("outputFilename"); } if (fileNames.Length == 0) { throw new ArgumentException("Length cannot be 0.", "fileNames"); } string newFilename = Path.Combine(directory, outputFilename); if (File.Exists(newFilename)) { File.Delete(newFilename); } using (FileStream fileStreamOut = File.Create(newFilename)) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStreamOut)) { zipOutputStream.SetLevel(9); foreach (string filename in fileNames) { ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename); zipOutputStream.PutNextEntry(zipEntry); using (FileStream fileStreamIn = File.OpenRead(Path.Combine(directory, filename))) { const long BUFFER_SIZE = 8192; long currentIndex = 0; byte[] buffer = new byte[BUFFER_SIZE]; if (fileStreamIn.Length <= BUFFER_SIZE) { fileStreamIn.Read(buffer, 0, Convert.ToInt32(fileStreamIn.Length)); zipOutputStream.Write(buffer, 0, Convert.ToInt32(fileStreamIn.Length)); } else { do { long remaining = BUFFER_SIZE; if (currentIndex + BUFFER_SIZE >= fileStreamIn.Length) { remaining = fileStreamIn.Length - currentIndex; } fileStreamIn.Read(buffer, 0, Convert.ToInt32(remaining)); currentIndex += remaining; zipOutputStream.Write(buffer, 0, Convert.ToInt32(remaining)); } while (currentIndex < fileStreamIn.Length); } } // using ( FileStream fileStreamIn = File.OpenRead( Path.Combine( directory, filename ) ... } // foreach zipOutputStream.Flush(); zipOutputStream.Finish(); } //using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ... } // using ( FileStream fileStreamOut = File.Create( newFilename ) ... }
protected void btnExport_Click(object sender, EventArgs e) { string xType = ddlExportType.SelectedItem.Text; bool xPack = ckbExportMulti.Checked; if (xPack) { Master.Log.Info("Creating package: " + txtZipName.Text); if (txtZipName.Text == "") { lblFNError.Visible = true; return; } else { lblFNError.Visible = false; } using (MemoryStream OutputStream = new MemoryStream()) { // Setup Zip Stream string zipFileName = txtZipName.Text + ".osapkg"; ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(OutputStream); zipStream.SetLevel(3); zipStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.On; // Add each object on list to Zip in reverse order. int lstCount = lstFileList.Items.Count; if (lstCount > 0) { //foreach (ListItem lstItem in lstFileList.Items) while (lstCount > 0) { ListItem lstItem = lstFileList.Items[lstCount - 1]; int iSplit = lstItem.Text.IndexOf("::"); string[] args = new string[2]; //lstItem.Text.Split(':',':'); args[0] = lstItem.Text.Substring(0, iSplit); args[1] = lstItem.Text.Substring(iSplit + 2); ExportObject xObj = new ExportObject(args[0], args[1]); Master.Log.Info("Adding file: " + xObj.ExportFileName + " to package: " + txtZipName.Text); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(xObj.ExportFileName); zipEntry.DateTime = DateTime.Now; zipEntry.Size = xObj.byteData.Length; zipStream.PutNextEntry(zipEntry); zipStream.Write(xObj.byteData, 0, xObj.byteData.Length); zipStream.Flush(); zipStream.CloseEntry(); lstCount = lstCount - 1; } } // Finish up Zip zipStream.IsStreamOwner = false; zipStream.Close(); OutputStream.Position = 0; byte[] byteArray = OutputStream.GetBuffer(); Int64 leng = byteArray.Length; Response.Clear(); Response.AppendHeader("Content-Disposition", "attachment; filename=" + zipFileName); Response.AppendHeader("Content-Length", leng.ToString()); Response.ContentType = "application/zip"; Response.BinaryWrite(byteArray); Response.Flush(); Master.Log.Info("Exported package: " + txtZipName.Text + " - By User: "******"Username"]); } } else { // Only 1 File lstFileList.Items.Clear(); ExportObject sExport = new ExportObject(ddlObjToExport.SelectedValue, ddlExportType.SelectedValue); Master.Log.Info("Exporting File: " + sExport.ExportFileName + " - By User: "******"Username"]); Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=\"" + sExport.ExportFileName + "\""); Response.Charset = ""; if (sExport.DataType == "Text") { Response.ContentType = "application/text"; StringBuilder sb = new StringBuilder(sExport.stringData); Response.Output.Write(sb.ToString()); } else if (sExport.Type == "Image") { Response.ContentType = "image/" + Path.GetExtension(sExport.ExportFileName); Response.BinaryWrite(sExport.byteData); } else { Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Length", sExport.ByteSize.ToString()); Response.BinaryWrite(sExport.byteData); } Response.Flush(); Response.End(); //Master.Log.Info("Exported file: " + sExport.ExportFileName + " - By User: "******"Username"]); } btnClear_Click(this, null); }
} // Unpack /// <summary> /// Zip a file. /// </summary> /// <param name="filename"></param> /// <param name="appendZipExtension"></param> public static void PackFile(string filename, bool appendZipExtension) { if (filename == null) { throw new ArgumentNullException("filename"); } if (!File.Exists(filename)) { throw new ArgumentException(string.Format("File does not exist: {0}.", filename), "filename"); } string newFilename = filename + ".zip"; if (!appendZipExtension) { newFilename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".zip"; } if (File.Exists(newFilename)) { File.Delete(newFilename); } FileStream fileStreamOut = File.Create(newFilename); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStreamOut); zipOutputStream.SetLevel(9); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filename)); zipOutputStream.PutNextEntry(zipEntry); FileStream fileStreamIn = File.OpenRead(filename); const long BUFFER_SIZE = 8192; long currentIndex = 0; byte[] buffer = new byte[BUFFER_SIZE]; if (fileStreamIn.Length <= BUFFER_SIZE) { fileStreamIn.Read(buffer, 0, Convert.ToInt32(fileStreamIn.Length)); zipOutputStream.Write(buffer, 0, Convert.ToInt32(fileStreamIn.Length)); } else { do { long remaining = BUFFER_SIZE; if (currentIndex + BUFFER_SIZE >= fileStreamIn.Length) { remaining = fileStreamIn.Length - currentIndex; } fileStreamIn.Read(buffer, 0, Convert.ToInt32(remaining)); currentIndex += remaining; zipOutputStream.Write(buffer, 0, Convert.ToInt32(remaining)); } while (currentIndex < fileStreamIn.Length); } fileStreamIn.Close(); zipOutputStream.Flush(); zipOutputStream.Finish(); zipOutputStream.Close(); fileStreamOut.Close(); }// ZipFile