/// <summary> /// Creates a bundle containing version list delta and all data of files. /// </summary> /// <returns>The binary bundle.</returns> /// <param name="list">List needed to transferred.</param> public static byte[] CreateFileBundle(List<FileEvent> list) { using (MemoryStream ms = new MemoryStream()) using (ZipOutputStream zip = new ZipOutputStream(ms)) { ZipEntry block = new ZipEntry("vs"); zip.PutNextEntry(block); zip.WriteAllBytes(list.SerializeAsBytes()); zip.CloseEntry(); foreach (var sha1 in list.Where(x => x.SHA1 != null).Select(x => x.SHA1).Distinct()) { block = new ZipEntry(sha1); zip.PutNextEntry(block); zip.WriteAllBytes(File.ReadAllBytes(Config.MetaFolderData.File(sha1))); zip.CloseEntry(); } zip.Finish(); ms.Flush(); ms.Position = 0; return ms.ToArray(); } }
public void Save(Project project, string filename) { using (var zipStream = new ZipOutputStream(new FileStream(filename, FileMode.Create))) { zipStream.PutNextEntry(new ZipEntry("book.xml")); bookLoader.Save(project.Book, zipStream); zipStream.CloseEntry(); foreach (var file in project.Files) { zipStream.PutNextEntry(new ZipEntry(file.Filename)); fileController.WriteSupportFile(file, zipStream); zipStream.CloseEntry(); } } }
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; }
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(); }
// Compresses the supplied memory stream, naming it as zipEntryName, into a zip, // which is returned as a memory stream or a byte array. // public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) { MemoryStream outputMemStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression ZipEntry newEntry = new ZipEntry(zipEntryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); StreamUtils.Copy(memStreamIn, 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; return outputMemStream; // 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; }
private void CompressFilesToOneZipFile() { Log.LogMessage(MessageImportance.Normal, "Zipping " + Source.Length + " files to zip file " + Destination); using (var fsOut = File.Create(Destination)) // Overwrites previous file { using (var zipStream = new ZipOutputStream(fsOut)) { foreach (ITaskItem item in Source) { string inputPath = item.ItemSpec; zipStream.SetLevel(9); // Highest level of compression var inputFileInfo = new FileInfo(inputPath); // clean up name string pathInArchive = !string.IsNullOrEmpty(WorkingDirectory) ? GetPath(inputFileInfo.FullName, WorkingDirectory) : Path.GetFileName(inputFileInfo.FullName); var newEntry = new ZipEntry(pathInArchive) { DateTime = inputFileInfo.CreationTime }; zipStream.PutNextEntry(newEntry); var buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(inputPath)) ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer); zipStream.CloseEntry(); } zipStream.IsStreamOwner = true; zipStream.Close(); } } }
/// <summary> /// Создать архив /// </summary> /// <param name="InputFilePath">Входной файл</param> /// <param name="OutPutFilePath">Выходной архив с одним файлом</param> public static void CreateZip(string InputFilePath, string OutPutFilePath) { FileInfo outFileInfo = new FileInfo(OutPutFilePath); FileInfo inFileInfo = new FileInfo(InputFilePath); // Create the output directory if it does not exist if (!Directory.Exists(outFileInfo.Directory.FullName)) { Directory.CreateDirectory(outFileInfo.Directory.FullName); } // Compress using (FileStream fsOut = File.Create(OutPutFilePath)) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.UseZip64 = UseZip64.Off; zipStream.SetLevel(9); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(inFileInfo.Name); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(InputFilePath)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; zipStream.Close(); } } }
// 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(); } }
private static void CompressFolder(string path, ZipOutputStream zipStream) { string[] files = Directory.GetFiles(path); foreach (string filename in files) { FileInfo fi = new FileInfo(filename); int offset = _root.Length + 3; string entryName = filename.Substring(offset); entryName = ZipEntry.CleanName(entryName); ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[] folders = Directory.GetDirectories(path); foreach (string folder in folders) { CompressFolder(folder, zipStream); } }
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 (); }
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> /// Compresses the folder. /// </summary> /// <param name="path">Path.</param> /// <param name="zipStream">Zip stream.</param> /// <param name="folderOffset">Folder offset.</param> private static void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) { string[] files = Directory.GetFiles(path); foreach (string filename in files) { FileInfo fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity newEntry.Size = fi.Length; 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]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[ ] folders = Directory.GetDirectories(path); foreach (string folder in folders) { CompressFolder(folder, zipStream, folderOffset); } }
private void CompressFiles(IEnumerable<string> filePaths, ZipOutputStream zipStream) { foreach (var fullFileName in filePaths) { var fi = new FileInfo(fullFileName); var fileName = Path.GetFileName(fullFileName); var newEntry = new ZipEntry(fileName) {DateTime = fi.LastWriteTime, Size = fi.Length}; // Note the zip format stores 2 second granularity // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. // A password on the ZipOutputStream is required if using AES. // newEntry.AESKeySize = 256; // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, // you need to do one of the following: Specify UseZip64.Off, or set the Size. // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, // but the zip will be in Zip64 format which not all utilities can understand. // zipStream.UseZip64 = UseZip64.Off; zipStream.UseZip64 = UseZip64.Off; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs var buffer = new byte[4096]; using (var streamReader = File.OpenRead(fullFileName)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.Finish(); }
protected override ITaskResult<Nothing> SafeExecute(TaskContext context) { if (Destination == null) { throw new Exception("Destination file is not set"); } using (var zipStream = new ZipOutputStream(Destination.WriteStream)) { foreach (var fileToCompress in _sourceFiles) { var entry = new ZipEntry(fileToCompress.EntityPath) { Size = fileToCompress.File.Length }; zipStream.PutNextEntry(entry); using (var fileReadStream = fileToCompress.File.ReadStream) { fileReadStream.CopyTo(zipStream); } zipStream.CloseEntry(); } zipStream.IsStreamOwner = true; } return Success; }
public static void Main(string[] args) { var target = args[0]; var filter = FileFilterParser.Parse(args[1], GetRecursiveFilesInCwd()); using (var file = new FileStream(target, FileMode.Create)) { using (var writer = new ZipOutputStream(file)) { foreach (var kv in filter) { var fi = new FileInfo(kv.Key); var entry = new ZipEntry(kv.Value); entry.DateTime = fi.LastWriteTime; entry.Size = fi.Length; writer.PutNextEntry(entry); using (var streamReader = File.OpenRead(kv.Key)) { streamReader.CopyTo(writer); } writer.CloseEntry(); } writer.Close(); } } }
/// <summary> /// ファイルを圧縮 /// </summary> /// <param name="filename">ファイル名フルパス</param> /// <param name="offsetFolderName">圧縮時のルートフォルダのフルパス</param> /// <param name="zipStream">圧縮先のZipStream</param> public static void CompressFile(string filename, string offsetFolderName, ZipOutputStream zipStream) { //フォルダのオフセット値を取得 var folderOffset = offsetFolderName.Length + (offsetFolderName.EndsWith("\\") ? 0 : 1); //ファイル名の余計なパスを消す string entryName = filename.Substring(folderOffset); entryName = ZipEntry.CleanName(entryName); //圧縮するファイルを表示←非常に良くない Console.WriteLine(entryName); //ファイル情報書き込み var fi = new FileInfo(filename); var newEntry = new ZipEntry(entryName) { DateTime = fi.LastWriteTime, Size = fi.Length, }; zipStream.PutNextEntry(newEntry); //ファイル内容書き込み var buffer = new byte[4096]; using (var streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); }
// Recurses down the folder structure // private void CompressFile(string filename, ZipOutputStream zipStream, int fileOffset) { var fi = new FileInfo(filename); var entryName = Path.GetFileName(filename); // Makes the name in zip based on the folder entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction var newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. // newEntry.AESKeySize = 256; // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, // you need to do one of the following: Specify UseZip64.Off, or set the Size. // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, // but the zip will be in Zip64 format which not all utilities can understand. // zipStream.UseZip64 = UseZip64.Off; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs var buffer = new byte[4096]; using (var streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); }
public override void Export(Project project, Stream output) { using (var zipStream = new ZipOutputStream(output)) { HtmlExportController htmlExport = new HtmlExportController(project.Files.Where(f => Path.GetExtension(f.Filename).Equals("css")).Select(f => f.Filename).ToArray()); zipStream.PutNextEntry(new ZipEntry(htmlFilename)); htmlExport.Export(project, zipStream); zipStream.CloseEntry(); foreach (var file in project.Files) { zipStream.PutNextEntry(new ZipEntry(file.Filename)); fileController.WriteSupportFile(file, zipStream); zipStream.CloseEntry(); } } }
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)); }
public async Task SaveAsync() { var buffer = new byte[4096]; using (var zipStream = new ZipOutputStream(new FileStream(FileName, FileMode.Create)) { IsStreamOwner = true }) { zipStream.SetLevel(3); zipStream.PutNextEntry(new ZipEntry(Constants.TileSetJsonFileName) { DateTime = DateTime.Now }); await SaveTileSetJson(zipStream, buffer); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry(Constants.ImageFileName) { DateTime = DateTime.Now }); await SaveImageSource(zipStream, TilesEditor.CreateMergedTileImage(), buffer); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry(Constants.ExtraImageFileName) { DateTime = DateTime.Now }); await SaveImageSource(zipStream, ExtraImagesEditor.CreateMergedExtraImage(), buffer); zipStream.CloseEntry(); } }
public static void CompessFileFromData(ZipOutputStream zipStream, string filename, byte[] data) { ZipEntry newZipEntry = new ZipEntry(filename); newZipEntry.Size = data.Length; zipStream.PutNextEntry(newZipEntry); zipStream.Write(data, 0, data.Length); zipStream.CloseEntry(); }
internal static byte[] Compress(byte[] asmBytes) { MemoryStream ms = new MemoryStream(); using (ZipOutputStream zos = new ZipOutputStream(ms)) { ZipEntry ze = new ZipEntry("file"); ze.Size = asmBytes.Length; zos.PutNextEntry(ze); zos.Write(asmBytes, 0, asmBytes.Length); zos.CloseEntry(); } return ms.ToArray(); }
/// <summary> /// Configure a .dll assembly file as the new cloud service assembly. /// </summary> public void UploadApplicationSingleDll(byte[] data, string fileName) { using (var tempStream = new MemoryStream()) { using (var zip = new ZipOutputStream(tempStream)) { zip.PutNextEntry(new ZipEntry(fileName)); zip.Write(data, 0, data.Length); zip.CloseEntry(); } UploadApplicationZipContainer(tempStream.ToArray()); } }
/// <summary> /// Creates a ZIP archive using the specified dictionary. /// The keys in the dictionary are the paths of the files as they should appear in the archive. /// The values in the dictionary are the absolute paths to the files on the local filesystem. /// </summary> /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.-or- <paramref name="archiveFilePath" /> specified a file that is read-only. </exception> /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. </exception> /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive). </exception> /// <exception cref="IOException">An I/O error occurred while creating the file. </exception> /// <exception cref="NotSupportedException"><paramref name="archiveFilePath" /> is in an invalid format. </exception> /// <exception cref="SecurityException">The caller does not have the required permission. </exception> /// <exception cref="FileNotFoundException">One of the elements within <paramref name="zipContents" /> points to a file that does not exist. </exception> public static void CreateZip(String archiveFilePath, Dictionary<String, String> zipContents) { using (FileStream fsOut = File.Create(archiveFilePath)) { var zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(9); // Compression Level: Valid range is 0-9, with 9 being the highest level of compression. foreach (var content in zipContents) { String archivePath = content.Key; // The location of the file as it appears in the archive. String filePath = content.Value; // The location of the file as it exists on disk. // Skip files that have no path. if (String.IsNullOrWhiteSpace(filePath)) { continue; } // Skip files that do not exist. if (!File.Exists(filePath)) { continue; } FileInfo fi = new FileInfo(filePath); // Makes the name in zip based on the folder String entryName = archivePath; // Removes drive from name and fixes slash direction entryName = ZipEntry.CleanName(entryName); var newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; // Note: Zip format stores 2 second granularity newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs var buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filePath)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); zipStream.Dispose(); } }
/// <summary> /// Compresses the dataset. /// </summary> /// <param name="ds">The target dataset.</param> /// <returns></returns> public static byte[] CompressDS( DataSet ds ) { MemoryStream ms = new MemoryStream(); ZipOutputStream zos = new ZipOutputStream( ms ); zos.PutNextEntry( new ZipEntry( ds.DataSetName ) ); BinaryFormatter bf = new BinaryFormatter(); DataSetSurrogate dss = new DataSetSurrogate( ds ); bf.Serialize( zos , dss ); zos.CloseEntry(); zos.Close(); byte[] ret = ms.ToArray(); ms.Close(); return ret; }
private static void PutFileToZip(string fileName, string entryName, ZipOutputStream zip) { FileInfo fileInfo = new FileInfo(fileName); ZipEntry entry = new ZipEntry(entryName); entry.DateTime = DateTime.Now; entry.Size = fileInfo.Length; zip.PutNextEntry(entry); byte[] buffer = new byte[4096]; using (FileStream stream = File.OpenRead(fileName)) { StreamUtils.Copy(stream, zip, buffer); } zip.CloseEntry(); }
/// <summary> /// Copy all files (except vstemplate) in the given folder and sub-folders to the given zip. /// </summary> private static void CopyFilesToZip(string folder, string zipFolder, ZipOutputStream zipStream) { // Files foreach (var file in Directory.GetFiles(folder).Where(x => !x.EndsWith(".vstemplate"))) { zipStream.PutNextEntry(new ZipEntry(zipFolder + Path.GetFileName(file))); var data = File.ReadAllBytes(file); zipStream.Write(data, 0, data.Length); zipStream.CloseEntry(); } // Sub folders foreach (var subFolder in Directory.GetDirectories(folder)) { CopyFilesToZip(subFolder, zipFolder + "/" + Path.GetFileName(subFolder), zipStream); } }
public static void CompessFile(ZipOutputStream zipStream, string filename, string zipFilename) { FileInfo fi = new FileInfo(filename); ZipEntry newZipEntry = new ZipEntry(zipFilename); newZipEntry.Size = fi.Length; zipStream.PutNextEntry(newZipEntry); byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); }
/// <summary> /// Build the template and save the resulting ZIP in the given folder. /// </summary> public void Build(string targetFolder) { // Get template name var name = NamePrefix + Path.GetFileName(sourceFolder); // Load the template file var template = XDocument.Parse(LoadVsTemplate()); var ns = template.Root.Name.NamespaceName; var projectType = template.Descendants(XName.Get("ProjectType", ns)).Single().Value; // Update wizard assembly foreach (var wizardE in template.Root.Descendants(XName.Get("WizardExtension", ns))) { var assemblyE = wizardE.Element(XName.Get("Assembly", ns)); if ((assemblyE != null) && string.IsNullOrEmpty(assemblyE.Value)) { var version = Assembly.GetExecutingAssembly().GetName().Version; assemblyE.Value = string.Format("Dot42.VStudio10.Editors, Version={0}, Culture=neutral, PublicKeyToken=0a72796057571e65", version); } } var templateContent = template.ToString(); // Ensure target folder exists var folder = Path.Combine(Path.Combine(Path.Combine(targetFolder, projectType), NamePrefix), Lcid); Directory.CreateDirectory(folder); // Create ZIP file. var path = Path.Combine(folder, name + ".zip"); using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { using (var zipStream = new ZipOutputStream(fileStream) {UseZip64 = UseZip64.Off}) { zipStream.SetLevel(9); // Add template zipStream.PutNextEntry(new ZipEntry(name + ".vstemplate")); var templateData = Encoding.UTF8.GetBytes(templateContent); zipStream.Write(templateData, 0, templateData.Length); zipStream.CloseEntry(); // Add remaining files CopyFilesToZip(sourceFolder, string.Empty, zipStream); } } }
public void TestCreateExtractor() { using (var tempDir = new TemporaryDirectory("0install-unit-tests")) { string path = Path.Combine(tempDir, "a.zip"); using (var file = File.Create(path)) using (var zipStream = new ZipOutputStream(file) {IsStreamOwner = false}) { var entry = new ZipEntry("file"); zipStream.PutNextEntry(entry); zipStream.CloseEntry(); } using (var extractor = Extractor.FromStream(File.OpenRead(path), tempDir, Model.Archive.MimeTypeZip)) Assert.IsInstanceOf(typeof(ZipExtractor), extractor); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Bitmap map = Properties.Resources.DerethMapDark; DirectoryInfo baseDir = new DirectoryInfo("DerethMap"); if (baseDir.Exists) baseDir.Delete(true); baseDir.Create(); string basePath = baseDir.FullName; TextWriter mapTxt = new StreamWriter(File.Create(Path.Combine(basePath, "map.txt"))); mapTxt.WriteLine(map.Width.ToString()); mapTxt.WriteLine(TileSize.ToString()); mapTxt.WriteLine(TilePadding.ToString()); mapTxt.Dispose(); Bitmap lowRes = new Bitmap((int)Math.Ceiling(map.Width / 2.0), (int)Math.Ceiling(map.Height / 2.0), PixelFormat.Format32bppArgb); Graphics resizer = Graphics.FromImage(lowRes); resizer.InterpolationMode = InterpolationMode.HighQualityBicubic; resizer.DrawImage(map, new Rectangle(new Point(0, 0), lowRes.Size)); lowRes.Save(Path.Combine(basePath, "lowres.png")); TileGen(map, 1, TileSize, TilePadding, basePath, "{0},{1}.png"); if (File.Exists("DerethMap.zip")) File.Delete("DerethMap.zip"); ZipOutputStream zip = new ZipOutputStream(File.Create("DerethMap.zip")); zip.Password = ""; foreach (FileInfo file in baseDir.GetFiles()) { ZipEntry ze = new ZipEntry(file.Name); zip.PutNextEntry(ze); FileStream rdr = file.OpenRead(); byte[] buffer = new byte[rdr.Length]; rdr.Read(buffer, 0, buffer.Length); rdr.Dispose(); zip.Write(buffer, 0, buffer.Length); zip.CloseEntry(); } zip.Close(); System.Media.SystemSounds.Asterisk.Play(); }
public static byte[] Zip(this byte[] data) { using (var @in = new MemoryStream(data)) { using (var @out = new MemoryStream()) { using (var zipStream = new ZipOutputStream(@out)) { zipStream.SetLevel(3); zipStream.PutNextEntry(new ZipEntry(Guid.NewGuid().ToString())); StreamUtils.Copy(@in, zipStream, new byte[4096]); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; zipStream.Close(); return @out.ToArray(); } } } }
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); }
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); }