/// <summary> /// Creates a zip archive from a byte array /// </summary> /// <param name="buffer">The file in byte[] format</param> /// <param name="fileName">The name of the file you want to add to the archive</param> /// <returns></returns> public static byte[] CreateZipByteArray(byte[] buffer, string fileName) { ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream()) { ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream); zipOutputStream.SetLevel(6); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); zipEntry.DateTime = DateTime.Now; zipEntry.Size = buffer.Length; crc.Reset(); crc.Update(buffer); zipEntry.Crc = crc.Value; zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.Write(buffer, 0, buffer.Length); zipOutputStream.Finish(); byte[] zipByteArray = new byte[zipMemoryStream.Length]; zipMemoryStream.Position = 0; zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length); zipOutputStream.Close(); return zipByteArray; } }
/// <summary> /// Create a zip file of the supplied file names and string data source /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully creating the zip file.</returns> public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData) { try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { stream.SetLevel(0); foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); var data = filenamesAndData[filename]; var bytes = Encoding.Default.GetBytes(data); stream.PutNextEntry(entry); stream.Write(bytes, 0, bytes.Length); stream.CloseEntry(); } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); return false; } return true; }
/// <summary> /// Zips the specified <paramref name="baseFolder"/> to the <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to write the compressed data to.</param> /// <param name="baseFolder">The folder to zip</param> /// <param name="filesToZip"> /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. /// These names are only matched in the <paramref name="baseFolder"/> but not recursive. /// You can use the default globbing (* and ?). /// </param> /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param> public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore) { using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream)) { s.SetLevel(9); s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; var baseDir = new DirectoryInfo(baseFolder); foreach (var fileMask in filesToZip) { foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue; var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name); s.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(s); } foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue; ZipDirectory(s, baseDir, subDir, filesToIgnore); } } s.Finish(); } }
/// <summary> /// Create a zip file of the supplied file names and string data source /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully creating the zip file.</returns> public static bool ZipData(string zipPath, Dictionary <string, string> filenamesAndData) { try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { stream.SetLevel(0); foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); var data = filenamesAndData[filename]; var bytes = Encoding.Default.GetBytes(data); stream.PutNextEntry(entry); stream.Write(bytes, 0, bytes.Length); stream.CloseEntry(); } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); return(false); } return(true); }
/// <summary> /// 边打包边下载, /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment;filename=Http.File.zip"); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream); zipStream.SetLevel(6); string rootPath = System.Web.HttpRuntime.BinDirectory; var filePaths = System.IO.Directory.GetFiles(rootPath, "*", System.IO.SearchOption.AllDirectories); foreach (var filePath in filePaths) { string entryName = filePath.Replace(rootPath, string.Empty).TrimStart('\\'); zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName)); using (var fs = System.IO.File.Open(filePath, System.IO.FileMode.Open)) { var bufferSize = 80 * 1024; var buffer = new byte[bufferSize]; int length = -1; while ((length = fs.Read(buffer, 0, bufferSize)) > 0) { zipStream.Write(buffer, 0, length); context.Response.Flush(); } } } zipStream.Finish(); context.Response.End(); }
/// <summary> /// Zips the specified <paramref name="baseFolder"/> to the <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to write the compressed data to.</param> /// <param name="baseFolder">The folder to zip</param> /// <param name="filesToZip"> /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. /// These names are only matched in the <paramref name="baseFolder"/> but not recursive. /// You can use the default globbing (* and ?). /// </param> /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param> public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore) { using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream)) { s.SetLevel(9); s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; var baseDir = new DirectoryInfo(baseFolder); foreach (var fileMask in filesToZip) { foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) { continue; } var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name); s.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(s); } foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) { continue; } ZipDirectory(s, baseDir, subDir, filesToIgnore); } } s.Finish(); } }
bool Zip() { var xapName = XapFilename.ItemSpec; if (File.Exists(xapName)) { DateTime lastMod = File.GetLastWriteTime(xapName); bool needsWrite = false; foreach (ITaskItem file_item in InputFiles) { if (File.GetLastWriteTime(file_item.ItemSpec) > lastMod) { needsWrite = true; break; } } if (!needsWrite) { Log.LogMessage(MessageImportance.Low, "Skipping xap file {0} generation, its up-to date"); return(true); } } Log.LogMessage(MessageImportance.Normal, "Generating compressed xap file {0}", xapName); try { using (FileStream fs = new FileStream(xapName, FileMode.Create)) { var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs); zip_stream.SetLevel(9); AddFilesToZip(InputFiles, zip_stream); AddFilesToZip(LocalCopyReferences, zip_stream); zip_stream.Finish(); zip_stream.Close(); } } catch (IOException ex) { Log.LogError("Error writing xap file.", ex); Log.LogMessage(MessageImportance.Low, "Error writing xap file:" + ex.ToString()); try { if (File.Exists(xapName)) { File.Delete(xapName); } } catch {} return(false); } return(true); }
/// <summary> /// 压缩文件,只支持zip压缩 /// </summary> /// <param name="fileAbsolutePathList">文件绝对路径的列表</param> /// <param name="compressFileName">压缩后文件的名称</param> /// <param name="isCoverOrNew">true为覆盖,false为新建</param> /// <returns></returns> public static string CompressFiles(List <string> fileAbsolutePathList, List <string> fileNameList, string compressFileName, bool isCoverOrNew) { if (fileAbsolutePathList == null || fileAbsolutePathList.Count < 1) { throw new Exception("至少传入一个文件或文件夹的绝对路径!"); } string firstPath = fileAbsolutePathList[0].Replace('/', '\\'); string dirPath = firstPath.Substring(0, firstPath.LastIndexOf('\\') + 1); if (string.IsNullOrEmpty(compressFileName)) { compressFileName = firstPath.Substring(firstPath.LastIndexOf('\\'));//取出最后一个\后面的字符串 作为文件名 if (System.IO.File.Exists(firstPath)) { compressFileName = compressFileName.Substring(0, compressFileName.LastIndexOf('.'));//去除文件名的扩展名 } } if (!Path.IsPathRooted(compressFileName)) { compressFileName = GetNewFilePath(dirPath, compressFileName + ".zip", isCoverOrNew); //获取合法的文件名 } ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(new FileStream(compressFileName, FileMode.Create)); //新建压缩文件流 “ZipOutputStream” try { zipOutput.SetLevel(9); //压缩等级 for (int i = 0; i < fileAbsolutePathList.Count; i++) { if (fileNameList == null || fileNameList.Count != fileAbsolutePathList.Count) { appendStream(zipOutput, fileAbsolutePathList[i], dirPath); } else { appendStream(zipOutput, fileAbsolutePathList[i], fileNameList[i], dirPath); } } zipOutput.Finish(); } catch (Exception ex) { throw ex; } finally { zipOutput.Close(); zipOutput.Dispose(); } return(compressFileName); }
private void DownloadZip(HttpContext context, List <Fe> lstfe) { //找出所有文件记录,2种可能情况, //1,按文件id, var lstfileId = lstfe.Where(x => x.cc == "file").Select(x => x.id).Distinct().ToList(); var lstFileEntity1 = this.dbcontext.FileEntity.Where(x => x.UploadStepValue == Model.UploadStep.完成).Where(x => lstfileId.Contains(x.Id)).ToList(); //2,按父目录 var lstdir = lstfe.Where(x => x.cc == "dir").Select(x => x.path).Distinct().ToList(); var lstdir2 = lstdir.Select(x => x + "\\").ToList(); var lstFileEntity2 = lstdir2.Select(x => this.dbcontext.FileEntity.Where(a => a.UploadStepValue == Model.UploadStep.完成).Where(a => a.FullName.StartsWith(x)).ToList()) .SelectMany(x => x) .ToList(); lstFileEntity1.AddRange(lstFileEntity2); var lstFileEntity = lstFileEntity1.GroupBy(x => x.Id).Select(gp => gp.First()).ToList(); context.Response.ContentType = "application/octet-stream"; string rpath = context.Request["rpath"] ?? string.Empty; string bundleName = rpath == string.Empty ? "root" : System.IO.Path.GetFileName(rpath); context.Response.AddHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + context.Server.UrlEncode(bundleName + "-bundle.zip")); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream); zipStream.SetLevel(6); string rootPath = this.GetRootFolder(context); string basepath = System.IO.Path.Combine(rootPath, rpath); var filePaths = lstFileEntity.Select(x => System.IO.Path.Combine(rootPath, x.FullName)).ToList(); foreach (var filePath in filePaths) { string entryName = filePath.Replace(basepath, string.Empty).TrimStart('\\'); zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName)); using (var fs = System.IO.File.Open(filePath, System.IO.FileMode.Open)) { var bufferSize = 1 * 1024 / 2; var buffer = new byte[bufferSize]; int length = -1; while ((length = fs.Read(buffer, 0, bufferSize)) > 0) { zipStream.Write(buffer, 0, length); context.Response.Flush(); } } } zipStream.Finish(); }
public static void ZipFile(System.Collections.Generic.List <string> filesToZip, string outFile, int compression = 3, bool IsMapPath = true) { outFile = IsMapPath ? TM.Core.IO.MapPath(outFile) : outFile; if (compression < 0 || compression > 9) { throw new ArgumentException("Invalid compression rate (just 0-9)."); } if (!Directory.Exists(new FileInfo(outFile).Directory.ToString())) { throw new ArgumentException("The Path does not exist."); } foreach (string c in filesToZip) { if (!File.Exists(IsMapPath ? TM.Core.IO.MapPath(c) : c)) { throw new ArgumentException(string.Format("The File {0} does not exist!", c)); } } var crc32 = new ICSharpCode.SharpZipLib.Checksum.Crc32(); var stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(outFile)); stream.SetLevel(compression); for (int i = 0; i < filesToZip.Count; i++) { var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filesToZip[i])); entry.DateTime = DateTime.Now; var _filesToZip = IsMapPath ? TM.Core.IO.MapPath(filesToZip[i]) : filesToZip[i]; using (FileStream fs = File.OpenRead(_filesToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry.Size = fs.Length; fs.Close(); crc32.Reset(); crc32.Update(buffer); entry.Crc = crc32.Value; stream.PutNextEntry(entry); stream.Write(buffer, 0, buffer.Length); } } stream.Finish(); stream.Close(); }
private void Compress(Stream data, Stream outData) { string str = ""; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("data.xml"); newEntry.DateTime = DateTime.UtcNow; //newEntry.Size = data.Length; zipStream.PutNextEntry(newEntry); //data.CopyTo(zipStream); //CopyStream(data, zipStream); //zipStream.Write(data, 0, data.Length); // zipStream.Finish(); //zipStream.Close();//? //byte[] buffer = new byte[32768]; //int read; //while ((read = data.Read(buffer, 0, buffer.Length)) > 0) //{ // zipStream.Write(buffer, 0, read); //} data.Position = 0; int size = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000; byte[] buffer = new byte[size]; int n; do { n = data.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, n); } while (n != 0); zipStream.CloseEntry(); zipStream.Flush(); zipStream.Close(); } } catch (Exception ex) { str = ex.Message; } }
/// <summary> /// 压缩多个文件 /// </summary> /// <param name="files">文件名</param> /// <param name="ZipedFileName">压缩包文件名</param> /// <param name="Password">解压码</param> /// <returns></returns> public static void Zip(string[] files, string ZipedFileName, string Password) { files = files.Where(f => System.IO.File.Exists(f) || System.IO.Directory.Exists(f)).ToArray(); if (files.Length == 0) { throw new System.IO.FileNotFoundException("未找到指定打包的文件"); } ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(ZipedFileName)); s.SetLevel(6); if (!string.IsNullOrEmpty(Password.Trim())) { s.Password = Password.Trim(); } Zip(files, s); s.Finish(); s.Close(); }
bool Zip () { var xapName = XapFilename.ItemSpec; if (File.Exists (xapName)) { DateTime lastMod = File.GetLastWriteTime (xapName); bool needsWrite = false; foreach (ITaskItem file_item in InputFiles) { if (File.GetLastWriteTime (file_item.ItemSpec) > lastMod) { needsWrite = true; break; } } if (!needsWrite) { Log.LogMessage (MessageImportance.Low, "Skipping xap file {0} generation, its up-to date"); return true; } } Log.LogMessage (MessageImportance.Normal, "Generating compressed xap file {0}", xapName); try { using (FileStream fs = new FileStream (xapName, FileMode.Create)) { var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs); zip_stream.SetLevel (9); AddFilesToZip (InputFiles, zip_stream); AddFilesToZip (LocalCopyReferences, zip_stream); zip_stream.Finish (); zip_stream.Close (); } } catch (IOException ex) { Log.LogError ("Error writing xap file.", ex); Log.LogMessage (MessageImportance.Low, "Error writing xap file:" + ex.ToString ()); try { if (File.Exists (xapName)) File.Delete (xapName); } catch {} return false; } return true; }
public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList) { System.Web.HttpContext.Current.Response.ContentType = "application/zip"; // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that //Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); System.Web.HttpContext.Current.Response.CacheControl = "Private"; System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(5)); // or put a timestamp in the filename in the content-disposition byte[] buffer = new byte[4096]; var zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.Web.HttpContext.Current.Response.OutputStream); zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression foreach (string fileName in zipFileList) { Stream fs = File.OpenRead(TM.IO.FileDirectory.MapPath(fileName)); // or any suitable inputstream var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fileName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!System.Web.HttpContext.Current.Response.IsClientConnected) { break; } System.Web.HttpContext.Current.Response.Flush(); } fs.Close(); } zipOutputStream.Close(); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); }
public static void CreateSample(string outPathname, string password, string folderName) { FileStream fsOut = File.Create(outPathname); var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES. // This setting will strip the leading part of the folder path in the entries, to // make the entries relative to the starting folder. // To include the full path for each entry up to the drive root, assign folderOffset = 0. int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); CompressFolder(folderName, zipStream, folderOffset); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); }
// public static byte[] Compress(byte[] data, string fileName) { // Compress using (MemoryStream fsOut = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); newEntry.DateTime = DateTime.UtcNow; newEntry.Size = data.Length; zipStream.PutNextEntry(newEntry); zipStream.Write(data, 0, data.Length); zipStream.Finish(); zipStream.Close(); } return(fsOut.ToArray()); } }
public static void Compress2(Stream data, Stream outData, string fileName) { string str = ""; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); data.CopyTo(zipStream); } } catch (Exception ex) { str = ex.Message; } }
public static byte[] CompressFile(byte[] data, string filename) { Stream stream = new MemoryStream(data); // Compress using (MemoryStream fsOut = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); StreamUtils.Copy(stream, zipStream, new byte[2048]); zipStream.Finish(); zipStream.Close(); } return(fsOut.ToArray()); } }
private byte[] CompressFile(byte[] data) { Stream stream = new MemoryStream(data); // Compress using (MemoryStream fsOut = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("data.xml"); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); //zipStream.Write(data, 0, data.Length); StreamUtils.Copy(stream, zipStream, new byte[2048]); zipStream.Finish(); zipStream.Close(); } return(fsOut.ToArray()); } }
/// <summary> /// Compacta a lista de Arquivos criando o arquivo zip passado como parâmetro /// </summary> /// <param name="filesName">Lista de arquivos a serem incluidos no .zip</param> /// <param name="strArquivoZip">Nome do arquivo .zip</param> public void compacta(ref System.Collections.ArrayList filesName, string strArquivoZip) { try { ICSharpCode.SharpZipLib.Checksums.Crc32 clsCrc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); ICSharpCode.SharpZipLib.Zip.ZipOutputStream clsZipOutStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(strArquivoZip)); clsZipOutStream.SetLevel(m_nNivelCompressao); foreach (string file in filesName) { System.IO.FileStream fs = System.IO.File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); clsCrc.Reset(); clsCrc.Update(buffer); entry.Crc = clsCrc.Value; clsZipOutStream.PutNextEntry(entry); clsZipOutStream.Write(buffer, 0, buffer.Length); } clsZipOutStream.Finish(); clsZipOutStream.Close(); } catch (Exception err) { Object erro = err; m_cls_ter_tratadorErro.trataErro(ref erro); } }
BuildResult Zip(IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf) { var xapName = GetXapName(proj, conf); var src = new List <string> (); var targ = new List <string> (); src.Add(conf.CompiledOutputName); targ.Add(conf.CompiledOutputName.FileName); // FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap, // when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers // that read pdb files don't expect them to be in the xap. var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime; if (doSdbCopy) { FilePath mdb = conf.CompiledOutputName + ".mdb"; if (File.Exists(mdb)) { src.Add(mdb); targ.Add(mdb.FileName); } } if (proj.GenerateSilverlightManifest) { src.Add(conf.OutputDirectory.Combine("AppManifest.xaml")); targ.Add("AppManifest.xaml"); } foreach (ProjectFile pf in proj.Files) { if (pf.BuildAction == BuildAction.Content) { src.Add(pf.FilePath); targ.Add(pf.ProjectVirtualPath); } } BuildResult res = new BuildResult(); // The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles. // Instead we need to iterate over the refs and handle them manually. foreach (ProjectReference pr in proj.References) { if (pr.LocalCopy) { var pk = pr.Package; if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith("-redist")) { string err = pr.ValidationErrorMessage; if (!String.IsNullOrEmpty(err)) { string msg = String.Format("Could not add reference '{0}' to '{1}': {2}", pr.Reference, xapName.FileName, err); res.AddError(msg); monitor.Log.WriteLine(msg); continue; } foreach (string s in pr.GetReferencedFileNames(slnConf)) { src.Add(s); targ.Add(Path.GetFileName(s)); if (doSdbCopy && s.EndsWith(".dll")) { FilePath mdb = s + ".mdb"; if (File.Exists(mdb)) { src.Add(mdb); targ.Add(mdb.FileName); } } } } } } if (res.ErrorCount > 0) { res.FailedBuildCount++; return(res); } if (File.Exists(xapName)) { DateTime lastMod = File.GetLastWriteTime(xapName); bool needsWrite = false; foreach (string file in src) { if (File.GetLastWriteTime(file) > lastMod) { needsWrite = true; break; } } if (!needsWrite) { return(null); } } monitor.Log.WriteLine("Compressing XAP file..."); try { using (FileStream fs = new FileStream(xapName, FileMode.Create)) { var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs); zipfile.SetLevel(9); byte[] buffer = new byte[4096]; for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++) { zipfile.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(targ[i])); using (FileStream inStream = File.OpenRead(src[i])) { int readCount; do { readCount = inStream.Read(buffer, 0, buffer.Length); zipfile.Write(buffer, 0, readCount); } while (readCount > 0); } } if (!monitor.IsCancelRequested) { zipfile.Finish(); zipfile.Close(); } } } catch (IOException ex) { monitor.ReportError("Error writing xap file.", ex); res.AddError("Error writing xap file:" + ex.ToString()); res.FailedBuildCount++; try { if (File.Exists(xapName)) { File.Delete(xapName); } } catch {} return(res); } if (monitor.IsCancelRequested) { try { if (File.Exists(xapName)) { File.Delete(xapName); } } catch {} } return(res); }
private static void compress_zip() { string zipPath = bset.zip_path; string zipFolder = bset.tmp_folder_path; //Write ZIP Stream. FileStream writer = new FileStream(zipPath, FileMode.Create, FileAccess.Write); //Build ZipOutputStream. ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer); //Set compress levels. if ((0 <= bset.compress) | (9 >= bset.compress)) { zos.SetLevel(bset.compress); } else { zos.SetLevel(9); } //Get folders. ICSharpCode.SharpZipLib.Zip.ZipNameTransform nameTrans = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(zipFolder); foreach (string file in Directory.EnumerateFiles(zipFolder, "*", System.IO.SearchOption.AllDirectories)) { if (file == bset.zip_path) { continue; } // Set file name. string f = nameTrans.TransformFile(file); ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(f); // Set file informations. FileInfo fi = new System.IO.FileInfo(file); ze.DateTime = fi.LastAccessTime; ze.ExternalFileAttributes = (int)fi.Attributes; ze.Size = fi.Length; ze.IsUnicodeText = true; zos.PutNextEntry(ze); // Load files. try { FileStream fs = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[2048]; int len; while ((len = fs.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, len); } fs.Close(); } catch (Exception ex) { Console.WriteLine(" - Error: " + file + " [" + ex.Message + "]"); continue; } } // Close objects. zos.Finish(); zos.Close(); writer.Close(); }
private void menuExportTeamData_Click(object sender, EventArgs e) { SaveFileDialog d = new SaveFileDialog(); d.AddExtension = true; d.DefaultExt = ".zip"; d.Filter = T("Tutti i file ZIP (*.zip)")+"|*.zip"; d.FileName = "RMO-Team-Data-" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip"; d.InitialDirectory = My.Dir.Desktop; d.OverwritePrompt = true; d.Title = T("Nome del file da esportare"); if (d.ShowDialog() == DialogResult.OK) { try { string[] filenames = System.IO.Directory.GetFiles(PATH_HISTORY, "*.team"); progressBar.Value = 0; progressBar.Maximum = filenames.Length; using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(d.FileName))) { s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string file in filenames) { ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (System.IO.FileStream fs = System.IO.File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } progressBar.Value++; } s.Finish(); s.Close(); lStatus.Text = T("Esportazione del backup ultimata correttamente!"); } } catch (Exception ex) { My.Box.Errore(T("Errore durante l'esportazione del backup")+"\r\n"+ex.Message); } progressBar.Value = 0; } }
internal void AddResources(Dictionary<string, List<ResourceItem>> resources, bool compressedResources) { Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources..."); // BUG we need to call GetTypeWrapperFactory() to make sure that the assemblyBuilder is created (when building an empty target) ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder; Dictionary<string, Dictionary<string, ResourceItem>> jars = new Dictionary<string, Dictionary<string, ResourceItem>>(); foreach (KeyValuePair<string, List<ResourceItem>> kv in resources) { foreach (ResourceItem item in kv.Value) { int count = 0; string jarName = item.jar; retry: Dictionary<string, ResourceItem> jar; if (!jars.TryGetValue(jarName, out jar)) { jar = new Dictionary<string, ResourceItem>(); jars.Add(jarName, jar); } if (jar.ContainsKey(kv.Key)) { jarName = Path.GetFileNameWithoutExtension(item.jar) + "-" + (count++) + Path.GetExtension(item.jar); goto retry; } jar.Add(kv.Key, item); } } foreach (KeyValuePair<string, Dictionary<string, ResourceItem>> jar in jars) { MemoryStream mem = new MemoryStream(); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(mem)) { foreach (KeyValuePair<string, ResourceItem> kv in jar.Value) { ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(kv.Key); if (kv.Value.zipEntry == null) { zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored; } else { zipEntry.Comment = kv.Value.zipEntry.Comment; zipEntry.CompressionMethod = kv.Value.zipEntry.CompressionMethod; zipEntry.DosTime = kv.Value.zipEntry.DosTime; zipEntry.ExternalFileAttributes = kv.Value.zipEntry.ExternalFileAttributes; zipEntry.ExtraData = kv.Value.zipEntry.ExtraData; zipEntry.Flags = kv.Value.zipEntry.Flags; } if (compressedResources || zipEntry.CompressionMethod != ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored) { zip.SetLevel(9); zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated; } zip.PutNextEntry(zipEntry); if (kv.Value.data != null) { zip.Write(kv.Value.data, 0, kv.Value.data.Length); } zip.CloseEntry(); } } mem = new MemoryStream(mem.ToArray()); string name = jar.Key; if (options.targetIsModule) { name = Path.GetFileNameWithoutExtension(name) + "-" + moduleBuilder.ModuleVersionId.ToString("N") + Path.GetExtension(name); } jarList.Add(name); moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public); } }
/// <summary> /// Creates a new Instance that will write to the specified stream /// </summary> /// <param name="stream">Stream to write the zipped data to</param> public ZipHelper(Stream stream) { zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); zipStream.SetLevel(9); zipStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; }
BuildResult Zip (IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf) { var xapName = GetXapName (proj, conf); var src = new List<string> (); var targ = new List<string> (); src.Add (conf.CompiledOutputName); targ.Add (conf.CompiledOutputName.FileName); // FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap, // when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers // that read pdb files don't expect them to be in the xap. var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime; if (doSdbCopy) { FilePath mdb = conf.CompiledOutputName + ".mdb"; if (File.Exists (mdb)) { src.Add (mdb); targ.Add (mdb.FileName); } } if (proj.GenerateSilverlightManifest) { src.Add (conf.OutputDirectory.Combine ("AppManifest.xaml")); targ.Add ("AppManifest.xaml"); } foreach (ProjectFile pf in proj.Files) { if (pf.BuildAction == BuildAction.Content) { src.Add (pf.FilePath); targ.Add (pf.ProjectVirtualPath); } } BuildResult res = new BuildResult (); // The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles. // Instead we need to iterate over the refs and handle them manually. foreach (ProjectReference pr in proj.References) { if (pr.LocalCopy) { var pk = pr.Package; if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith ("-redist")) { string err = pr.ValidationErrorMessage; if (!String.IsNullOrEmpty (err)) { string msg = String.Format ("Could not add reference '{0}' to '{1}': {2}", pr.Reference, xapName.FileName, err); res.AddError (msg); monitor.Log.WriteLine (msg); continue; } foreach (string s in pr.GetReferencedFileNames (slnConf)) { src.Add (s); targ.Add (Path.GetFileName (s)); if (doSdbCopy && s.EndsWith (".dll")) { FilePath mdb = s + ".mdb"; if (File.Exists (mdb)) { src.Add (mdb); targ.Add (mdb.FileName); } } } } } } if (res.ErrorCount > 0) { res.FailedBuildCount++; return res; } if (File.Exists (xapName)) { DateTime lastMod = File.GetLastWriteTime (xapName); bool needsWrite = false; foreach (string file in src) { if (File.GetLastWriteTime (file) > lastMod) { needsWrite = true; break; } } if (!needsWrite) return null; } monitor.Log.WriteLine ("Compressing XAP file..."); try { using (FileStream fs = new FileStream (xapName, FileMode.Create)) { var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs); zipfile.SetLevel (9); byte[] buffer = new byte[4096]; for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++) { zipfile.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (targ[i])); using (FileStream inStream = File.OpenRead (src[i])) { int readCount; do { readCount = inStream.Read (buffer, 0, buffer.Length); zipfile.Write (buffer, 0, readCount); } while (readCount > 0); } } if (!monitor.IsCancelRequested) { zipfile.Finish (); zipfile.Close (); } } } catch (IOException ex) { monitor.ReportError ("Error writing xap file.", ex); res.AddError ("Error writing xap file:" + ex.ToString ()); res.FailedBuildCount++; try { if (File.Exists (xapName)) File.Delete (xapName); } catch {} return res; } if (monitor.IsCancelRequested) { try { if (File.Exists (xapName)) File.Delete (xapName); } catch {} } return res; }
private void _CompressZIP(string pathFileZip, IDTSComponentEvents componentEvents) { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(_folderSource); System.IO.FileInfo[] fi_s = di.GetFiles("*.*", (_recurse ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly)); bool b = false; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream fz = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(pathFileZip))) { fz.SetLevel(9); if (!string.IsNullOrEmpty(_comment)) { componentEvents.FireInformation(1, "UnZip SSIS", "Set Comment.", null, 0, ref b); fz.SetComment(_comment); } if (!string.IsNullOrWhiteSpace(_password)) { componentEvents.FireInformation(1, "UnZip SSIS", "Set Password.", null, 0, ref b); fz.Password = _password; } foreach (System.IO.FileInfo fi in fi_s) { if (!System.Text.RegularExpressions.Regex.Match(fi.FullName, _fileFilter).Success) { componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": file " + fi.FullName + " doesn't match regex filter '" + _fileFilter + "'. File not processed.", null, 0, ref b); continue; } componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": Compress (with '" + _storePaths.ToString() + "') file: " + fi.FullName, null, 0, ref b); string file_name = ""; ICSharpCode.SharpZipLib.Zip.ZipEntry ze = null; if (_storePaths == Store_Paths.Absolute_Paths) { //Absolute Path file_name = ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fi.FullName); ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name); } else if (_storePaths == Store_Paths.Relative_Paths) { //Relative Path ICSharpCode.SharpZipLib.Zip.ZipNameTransform zn = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(_folderSource); file_name = zn.TransformFile(fi.FullName); if (_addRootFolder) { file_name = (di.Name + "/" + file_name).Replace("//", "/"); } ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name); } else if (_storePaths == Store_Paths.No_Paths) { //No Path file_name = fi.Name; ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name); } else { throw new Exception("Please select type Store Paths (No_Paths / Relative_Paths / Absolute_Paths)."); } using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { ze.Size = fs.Length; fz.PutNextEntry(ze); fs.CopyTo(fz); fs.Flush(); fz.Flush(); fz.CloseEntry(); } } fz.Flush(); } _Check_ZIP(pathFileZip, componentEvents); } catch (Exception ex) { componentEvents.FireError(1000, "UnZip SSIS", ex.Message, null, 0); throw; } finally { } }
} // End Sub CreateExe // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx // This will accumulate each of the files named in the fileList into a zip file, // and stream it to the browser. // This approach writes directly to the Response OutputStream. // The browser starts to receive data immediately which should avoid timeout problems. // This also avoids an intermediate memorystream, saving memory on large files. // public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ClearContent(); Response.ClearHeaders(); Response.Clear(); Response.Buffer = false; Response.ContentType = "application/zip"; // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that // Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); // Response.CacheControl = "Private"; // Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition // http://stackoverflow.com/questions/9303919/pack-empty-directory-with-sharpziplib byte[] buffer = new byte[4096]; using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream)) { zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression // zipOutputStream.Dispose // Empty folder... foreach (string directoryName in zipFileList) { string dname = "myfolder/"; ZipEntry entry = new ZipEntry(dname); // ZipEntry entry = new ZipEntry(ZipEntry.CleanName(dname)); // entry.Size = fs.Length; zipOutputStream.PutNextEntry(entry); } // Next directoryName foreach (string fileName in zipFileList) { // or any suitable inputstream using (System.IO.Stream fs = System.IO.File.OpenRead(fileName)) { ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!Response.IsClientConnected) { break; } Response.Flush(); } // Whend fs.Close(); } // End Using fs } // Next fileName zipOutputStream.Close(); } // End Using zipOutputStream Response.Flush(); Response.End(); } // End Function DownloadZipToBrowser
/// <summary> /// Creates a new Instance that will write to the specified stream /// </summary> /// <param name="stream">Stream to write the zipped data to</param> public ZipHelper(Stream stream) { zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); zipStream.SetLevel(9); zipStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; }
/// <summary> /// Constructs a new zip instance. /// If the file exists and has a non-zero length we read it, /// otherwise we create a new archive. /// Note that due to a bug with updating archives, an archive cannot be both read and write. /// </summary> /// <param name="file">The name of the file to read or write</param> /// <param name="options">The options passed on the commandline</param> public FileArchiveZip(string file, Dictionary<string, string> options) { if (!System.IO.File.Exists(file) || new System.IO.FileInfo(file).Length == 0) { #if SHARPZIPLIBWORKS m_zip = new FileArchiveZip(ICSharpCode.SharpZipLib.Zip.ZipFile.Create(filename)); m_zip.BeginUpdate(); #else m_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(file)); #endif int compressionLevel = DEFAULT_COMPRESSION_LEVEL; int tmplvl; string cplvl = null; if (options.TryGetValue(COMPRESSION_LEVEL_OPTION, out cplvl) && int.TryParse(cplvl, out tmplvl)) compressionLevel = Math.Max(Math.Min(9, tmplvl), 0); m_stream.SetLevel(compressionLevel); } else { m_zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(file); } }