/// <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(); } }
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> /// 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) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); //Get a Byte[] of the file data: var file = Encoding.Default.GetBytes(filenamesAndData[filename]); stream.PutNextEntry(entry); using (var ms = new MemoryStream(file)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); success = false; } return success; }
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()); } }
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; } }
protected virtual void SerializeHeightmap(Map map, Stream stream) { // Heightmap serialization method 3 var i = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap"); i.PutNextEntry(entry); var bw = new BinaryWriter(i); bw.Write(map.Ground.Heightmap.GetLength(0)); bw.Write(map.Ground.Heightmap.GetLength(1)); for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++) { for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++) { bw.Write(map.Ground.Heightmap[y, x].R); } } i.Close(); }
/// <summary> /// Compress a given file and delete the original file. Automatically rename the file to name.zip. /// </summary> /// <param name="textPath">Path of the original file</param> /// <param name="zipEntryName">The name of the entry inside the zip file</param> /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param> /// <returns>String path for the new zip file</returns> public static string Zip(string textPath, string zipEntryName, bool deleteOriginal = true) { var zipPath = ""; try { var buffer = new byte[4096]; zipPath = textPath.Replace(".csv", ".zip"); zipPath = zipPath.Replace(".txt", ".zip"); //Open the zip: using (var stream = new ZipOutputStream(File.Create(zipPath))) { //Zip the text file. var entry = new ZipEntry(zipEntryName); stream.PutNextEntry(entry); using (var fs = File.OpenRead(textPath)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); }while (sourceBytes > 0); } //Close stream: stream.Finish(); stream.Close(); } //Delete the old text file: if (deleteOriginal) { File.Delete(textPath); } } catch (Exception err) { Log.Error(err); } return(zipPath); }
/// <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) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); //Get a Byte[] of the file data: var file = Encoding.Default.GetBytes(filenamesAndData[filename]); stream.PutNextEntry(entry); using (var ms = new MemoryStream(file)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); }while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); success = false; } return(success); }
public static void CompressFolder(string path, ICSharpCode.SharpZipLib.Zip.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 = ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction var newEntry = new ICSharpCode.SharpZipLib.Zip.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. // 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; 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)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[] folders = Directory.GetDirectories(path); foreach (string folder in folders) { CompressFolder(folder, zipStream, folderOffset); } }
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> /// Create a zip file of the supplied file names and data using a byte array /// </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 saving the file</returns> public static bool ZipData(string zipPath, IEnumerable <KeyValuePair <string, byte[]> > filenamesAndData) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var file in filenamesAndData) { //Create the space in the zip file: var entry = new ZipEntry(file.Key); //Get a Byte[] of the file data: stream.PutNextEntry(entry); using (var ms = new MemoryStream(file.Value)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); }while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error("QC.Data.ZipData(): " + err.Message); success = false; } return(success); }
/// <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); } }
/// <summary> /// Zips the specified lines of text into the zipPath /// </summary> /// <param name="zipPath">The destination zip file path</param> /// <param name="zipEntry">The entry name in the zip</param> /// <param name="lines">The lines to be written to the zip</param> /// <returns>True if successful, otherwise false</returns> public static bool ZipData(string zipPath, string zipEntry, IEnumerable <string> lines) { try { using (var stream = new ZipOutputStream(File.Create(zipPath))) using (var writer = new StreamWriter(stream)) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); foreach (var line in lines) { writer.WriteLine(line); } } return(true); } catch (Exception err) { Log.Error(err); return(false); } }
/// <summary> /// Recursive Zipping of a directory. /// </summary> /// <param name="zipStream"></param> /// <param name="baseDir"></param> /// <param name="dir"></param> /// <param name="filesToIgnore"></param> private static void ZipDirectory(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, DirectoryInfo baseDir, DirectoryInfo dir, string[] filesToIgnore) { var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(baseDir.FullName); foreach (var file in dir.GetFiles()) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) { continue; } var relativeName = nameTransform.TransformFile(file.FullName); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName); zipStream.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream); } foreach (var subDir in dir.GetDirectories()) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) { continue; } ZipDirectory(zipStream, baseDir, subDir, filesToIgnore); } }
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); } }
public string ExportDetails(DataSet dataset, ExportFormat formatType, string filename) { if (dataset.Tables.Count < 2 && formatType == ExportFormat.CSV) { using (var writer = File.CreateText(filename)) { WriteCSV(dataset.Tables[0], writer); writer.Flush(); } return(filename); } if (formatType == ExportFormat.CSV) { //need to write each query result to a separate file and zip up if (System.IO.Path.GetExtension(filename) != "zip") { filename = Path.ChangeExtension(filename, "zip"); } using (var filestream = new FileStream(filename, FileMode.Create)) using (var zipstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(filestream)) { for (int i = 0; i < dataset.Tables.Count; i++) { var table = dataset.Tables[i]; string zipEntryFilename = Path.ChangeExtension(table.TableName, "csv"); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename); zipEntry.DateTime = DateTime.Now; zipstream.PutNextEntry(zipEntry); using (var writer = new StreamWriter(zipstream, Encoding.Default, 1024, true)) { WriteCSV(table, writer); writer.Flush(); } } } return(filename); } else if (formatType == ExportFormat.Excel) { //need to write each query result to a separate tab, with the tab name the queryname using (var filestream = File.Create(filename, 1024)) using (SpreadsheetDocument doc = SpreadsheetDocument.Create(filestream, SpreadsheetDocumentType.Workbook)) { WorkbookPart workbookPart = doc.AddWorkbookPart(); workbookPart.Workbook = new Workbook(); doc.WorkbookPart.Workbook.Sheets = new Sheets(); Sheets sheets = doc.WorkbookPart.Workbook.GetFirstChild <Sheets>(); var excelValidator = new Lpp.Utilities.Excel.ExcelEx(); for (uint sheetID = 1; sheetID <= dataset.Tables.Count; sheetID++) { var table = dataset.Tables[((int)sheetID) - 1]; WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>(); Sheet sheet = new Sheet { Id = doc.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = sheetID, Name = excelValidator.ValidateTabName(table.TableName) }; sheets.Append(sheet); SheetData sheetData = new SheetData(); worksheetPart.Worksheet = new Worksheet(sheetData); Row headerRow = new Row(); for (int i = 0; i < table.Columns.Count; i++) { headerRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(table.Columns[i].ColumnName) }); } sheetData.AppendChild(headerRow); Row dataRow; for (int j = 0; j < table.Rows.Count; j++) { dataRow = new Row(); var row = table.Rows[j]; for (int k = 0; k < row.ItemArray.Length; k++) { dataRow.AppendChild(new Cell { DataType = CellValues.String, CellValue = new CellValue(row.ItemArray[k].ToStringEx()) }); } sheetData.AppendChild(dataRow); } worksheetPart.Worksheet.Save(); } } return(filename); } else { throw new ArgumentOutOfRangeException(nameof(formatType), "formatType", "Invalid export format type value: " + formatType.ToString()); } }
public void ZipAdminFile(string strFile, List <string> filesExtra) { if (File.Exists(strFile)) { if (GetConfig().ZipAfterIndexed == true) { try { string zipFilePath = Path.ChangeExtension(strFile, ".zip"); if (File.Exists(zipFilePath)) { File.Delete(zipFilePath); } if (filesExtra == null) { filesExtra = new List <string>(); } if (strFile != null) { filesExtra.Add(strFile); } ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream); strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath)); if (GetConfig().CollapseFolders) { // minus.gif string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif"; if (File.Exists(f1)) { filesExtra.Add(f1); } string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif"; if (File.Exists(f2)) { filesExtra.Add(f2); } } if (File.Exists(GetConfig().LogoPath)) { filesExtra.Add(GetConfig().LogoPath); } foreach (string filePath in filesExtra) { FileStream strmFile = File.OpenRead(filePath); byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1]; strmFile.Read(abyBuffer, 0, abyBuffer.Length); ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath)); objZipEntry.DateTime = DateTime.Now; objZipEntry.Size = strmFile.Length; strmFile.Close(); strmZipOutputStream.PutNextEntry(objZipEntry); strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length); } ///''''''''''''''''''''''''''''''''' // Finally Close strmZipOutputStream ///''''''''''''''''''''''''''''''''' strmZipOutputStream.Finish(); strmZipOutputStream.Close(); if (GetConfig().ZipAndDeleteFile == true) { File.Delete(strFile); } } catch (System.UnauthorizedAccessException ex) { Debug.WriteLine(ex.ToString()); } } } }
/// <summary> /// Create a zip file of the supplied file names and data using a byte array /// </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 saving the file</returns> public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var file in filenamesAndData) { //Create the space in the zip file: var entry = new ZipEntry(file.Key); //Get a Byte[] of the file data: stream.PutNextEntry(entry); using (var ms = new MemoryStream(file.Value)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error("QC.Data.ZipData(): " + err.Message); success = false; } return success; }
/// <summary> /// Zips all files specified to a new zip at the destination path /// </summary> public static void ZipFiles(string destination, IEnumerable<string> files) { try { using (var zipStream = new ZipOutputStream(File.Create(destination))) { var buffer = new byte[4096]; foreach (var file in files) { if (!File.Exists(file)) { Log.Trace("ZipFiles(): File does not exist: " + file); continue; } var entry = new ZipEntry(Path.GetFileName(file)); zipStream.PutNextEntry(entry); using (var fstream = File.OpenRead(file)) { StreamUtils.Copy(fstream, zipStream, buffer); } } } } catch (Exception err) { Log.Error(err); } }
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(); }
/// <summary> /// Compress a given file and delete the original file. Automatically rename the file to name.zip. /// </summary> /// <param name="textPath">Path of the original file</param> /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param> /// <returns>String path for the new zip file</returns> public static string Zip(string textPath, bool deleteOriginal = true) { var zipPath = ""; try { var buffer = new byte[4096]; zipPath = textPath.Replace(".csv", ".zip"); zipPath = zipPath.Replace(".txt", ".zip"); //Open the zip: using (var stream = new ZipOutputStream(File.Create(zipPath))) { //Zip the text file. var entry = new ZipEntry(Path.GetFileName(textPath)); stream.PutNextEntry(entry); using (var fs = File.OpenRead(textPath)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } //Close stream: stream.Finish(); stream.Close(); } //Delete the old text file: if (deleteOriginal) File.Delete(textPath); } catch (Exception err) { Log.Error("QC.Data.Zip(): " + err.Message); } return zipPath; }
/// <summary> /// 压缩 /// </summary> /// <param name="zipStream">压缩流</param> /// <param name="filePath">文件或文件夹路径</param> /// <param name="rootDirPath">根路径(就是压缩后的文件存储的路径)</param> private static void appendStream(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, string filePath, string rootDirPath) { appendStream(zipStream, filePath, null, rootDirPath); }
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 { } }
/// <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); }
public static void InternalSaveMiniProject(IStorage pStgSave, AltaxoDocument projectToSave, string graphDocumentName) { ComDebug.ReportInfo("GraphDocumentDataObject.InternalSaveMiniProject BEGIN"); try { Exception saveEx = null; Ole32Func.WriteClassStg(pStgSave, typeof(GraphDocumentEmbeddedComObject).GUID); // Store the version of this assembly { var assembly = System.Reflection.Assembly.GetExecutingAssembly(); Version version = assembly.GetName().Version; using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoVersion", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true)) { string text = version.ToString(); byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(text); stream.Write(nameBytes, 0, nameBytes.Length); } } // Store the name of the item using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoGraphName", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true)) { byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(graphDocumentName); stream.Write(nameBytes, 0, nameBytes.Length); } // Store the project using (var stream = new ComStreamWrapper(pStgSave.CreateStream("AltaxoProjectZip", (int)(STGM.DIRECT | STGM.READWRITE | STGM.CREATE | STGM.SHARE_EXCLUSIVE), 0, 0), true)) { using (var zippedStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream)) { var zippedStreamWrapper = new Altaxo.Main.ZipOutputStreamWrapper(zippedStream); var info = new Altaxo.Serialization.Xml.XmlStreamSerializationInfo(); projectToSave.SaveToZippedFile(zippedStreamWrapper, info); zippedStream.Close(); } stream.Close(); } if (null != saveEx) throw saveEx; } catch (Exception ex) { ComDebug.ReportError("InternalSaveMiniProject, Exception ", ex); } finally { Marshal.ReleaseComObject(pStgSave); } ComDebug.ReportInfo("GraphDocumentDataObject.InternalSaveMiniProject END"); }
/// <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); } }
/// <summary> /// Performs an in memory zip of the specified bytes /// </summary> /// <param name="bytes">The file contents in bytes to be zipped</param> /// <param name="zipEntryName">The zip entry name</param> /// <returns>The zipped file as a byte array</returns> public static byte[] ZipBytes(byte[] bytes, string zipEntryName) { using (var memoryStream = new MemoryStream()) using (var stream = new ZipOutputStream(memoryStream)) { var entry = new ZipEntry(zipEntryName); stream.PutNextEntry(entry); var buffer = new byte[16*1024]; StreamUtils.Copy(new MemoryStream(bytes), stream, buffer); return memoryStream.GetBuffer(); } }
public void ZipAdminFile(string strFile, List<string> filesExtra) { if (File.Exists(strFile)) { if (GetConfig().ZipAfterIndexed == true) { try { string zipFilePath = Path.ChangeExtension(strFile, ".zip"); if (File.Exists(zipFilePath)) File.Delete(zipFilePath); if (filesExtra == null) { filesExtra = new List<string>(); } if (strFile != null) { filesExtra.Add(strFile); } ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream); strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath)); if (GetConfig().CollapseFolders) { // minus.gif string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif"; if (File.Exists(f1)) filesExtra.Add(f1); string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif"; if (File.Exists(f2)) filesExtra.Add(f2); } if (File.Exists(GetConfig().LogoPath)) { filesExtra.Add(GetConfig().LogoPath); } foreach (string filePath in filesExtra) { FileStream strmFile = File.OpenRead(filePath); byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1]; strmFile.Read(abyBuffer, 0, abyBuffer.Length); ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath)); objZipEntry.DateTime = DateTime.Now; objZipEntry.Size = strmFile.Length; strmFile.Close(); strmZipOutputStream.PutNextEntry(objZipEntry); strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length); } ///''''''''''''''''''''''''''''''''' // Finally Close strmZipOutputStream ///''''''''''''''''''''''''''''''''' strmZipOutputStream.Finish(); strmZipOutputStream.Close(); if (GetConfig().ZipAndDeleteFile == true) { File.Delete(strFile); } } catch (System.UnauthorizedAccessException ex) { Debug.WriteLine(ex.ToString()); } } } }
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; } }
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; }
// 패치할 파일들을 zip 으로 압축한다. List <PatchFileInfo> PatchFilesCompression_Zip() { List <PatchFileInfo> PatchFileInfoList = new List <PatchFileInfo>(); PatchFileInfo patchfileinfo = new PatchFileInfo(); // 사용법 http://dobon.net/vb/dotnet/links/sharpziplib.html // SharpZipLib 사이트 http://www.icsharpcode.net/OpenSource/SharpZipLib/ try { this.Cursor = Cursors.WaitCursor; //ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); string zipFullPathName = textBoxPackingFilesFolder.Text + @"\" + PackingFileName + ".zip"; System.IO.FileStream writer = new System.IO.FileStream(zipFullPathName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer); // 압축레벨을 설정 //zos.SetLevel(6); // 패스워드를 설정한다. //zos.Password = "******"; foreach (string file in PatchFileList) { int Substringindex = textBoxNextVerFolder.Text.Length; string f = file.Substring(Substringindex + 1); ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(f); System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); // CRC를 설정한다 //crc.Reset(); //crc.Update(buffer); //ze.Crc = crc.Value; // 사이즈를 설정한다 ze.Size = buffer.Length; // 시간을 설정한다 ze.DateTime = DateTime.Now; // 새로운 파일을 추가 zos.PutNextEntry(ze); // 쓰기 zos.Write(buffer, 0, buffer.Length); } zos.Close(); writer.Close(); patchfileinfo.FileName = new FileInfo(zipFullPathName).Name; patchfileinfo.FileCRC = GetCRC(zipFullPathName); patchfileinfo.FileSize = new FileInfo(zipFullPathName).Length; PatchFileInfoList.Add(patchfileinfo); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { this.Cursor = Cursors.Default; } return(PatchFileInfoList); }
} // 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
public static void Zip(string data, string zipPath, string zipEntry) { using (var stream = new ZipOutputStream(File.Create(zipPath))) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); var buffer = new byte[4096]; using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data))) { int sourceBytes; do { sourceBytes = dataReader.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } }
protected virtual void SerializeHeightmap(Map map, Stream stream) { // Heightmap serialization method 3 var i = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap"); i.PutNextEntry(entry); var bw = new BinaryWriter(i); bw.Write(map.Ground.Heightmap.GetLength(0)); bw.Write(map.Ground.Heightmap.GetLength(1)); for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++) for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++) bw.Write(map.Ground.Heightmap[y, x].R); i.Close(); }
/// <summary> /// Zips the specified lines of text into the zipPath /// </summary> /// <param name="zipPath">The destination zip file path</param> /// <param name="zipEntry">The entry name in the zip</param> /// <param name="lines">The lines to be written to the zip</param> /// <returns>True if successful, otherwise false</returns> public static bool ZipData(string zipPath, string zipEntry, IEnumerable<string> lines) { try { using (var stream = new ZipOutputStream(File.Create(zipPath))) using (var writer = new StreamWriter(stream)) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); foreach (var line in lines) { writer.WriteLine(line); } } return true; } catch (Exception err) { Log.Error(err); return false; } }
public static void CreateVersionWycFile() { { var fileStream = System.IO.File.Create("client.wyc"); var zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStream); { var iucMemoryStream = new System.IO.MemoryStream(); { //var fileStream = System.IO.File.Create("iuclient.iuc"); var fw = new wyUpdate.FileWriter(iucMemoryStream); fw.WriteHeader("IUCDFV2"); fw.WriteDeprecatedString(0x01, "RealmPlayers.com"); //Company Name fw.WriteDeprecatedString(0x02, "VF_WoWLauncher"); //Product Name fw.WriteDeprecatedString(0x03, StaticValues.LauncherVersion); //Installed Version //fw.WriteDeprecatedString(0x03, "0.9"); //Installed Version fw.WriteString(0x0A, "TestAnything"); //GUID of the product if (Settings.Instance.UpdateToBeta == true) { fw.WriteDeprecatedString(0x04, "ftp://[email protected]:5511/Updates/VF_WowLauncher/BetaUpdate.wys"); //Server File Site(s) } else { fw.WriteDeprecatedString(0x04, "ftp://[email protected]:5511/Updates/VF_WowLauncher/Update.wys"); //Server File Site(s) } fw.WriteDeprecatedString(0x09, "ftp://[email protected]:5511/Updates/wyUpdate/Update.wys"); //wyUpdate Server Site(s) (can add any number of theese) fw.WriteDeprecatedString(0x11, "Left"); //Header Image Alignment Either "Left", "Right", "Fill" fw.WriteInt(0x12, 4); //Header text indent fw.WriteDeprecatedString(0x13, "Black"); //Header text color (Black, White, Red etc etc etc) fw.WriteDeprecatedString(0x14, "HeaderImage.png"); //Header filename fw.WriteDeprecatedString(0x15, "LeftImage.png"); //Side image filename fw.WriteDeprecatedString(0x18, "en-US"); //Language Culture (e.g. en-US or fr-FR) fw.WriteBool(0x17, false); //Hide header divider? (default = false) fw.WriteBool(0x19, false); //Close wyUpdate on successful update fw.WriteString(0x1A, "VF_WoWLauncher Updater"); //Custom wyUpdate title bar //WriteFiles.WriteString(fileStream, 0x1B, "DilaPublicSignKey"); //Public sign key -- DENNA MÅSTE VARA KORREKT ANNARS FAILAR SHA1!!!!! iucMemoryStream.WriteByte(0xFF); //fileStream.Close(); } var byteArray = iucMemoryStream.ToArray(); var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("iuclient.iuc"); newEntry.Size = byteArray.Length; zipOutputStream.PutNextEntry(newEntry); zipOutputStream.Write(byteArray, 0, byteArray.Length); zipOutputStream.CloseEntry(); } { var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("HeaderImage.png"); newEntry.Size = Properties.Resources.HeaderImagepng.Length; zipOutputStream.PutNextEntry(newEntry); zipOutputStream.Write(Properties.Resources.HeaderImagepng, 0, Properties.Resources.HeaderImagepng.Length); zipOutputStream.CloseEntry(); } { var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("LeftImage.png"); newEntry.Size = Properties.Resources.LeftImagepng.Length; zipOutputStream.PutNextEntry(newEntry); zipOutputStream.Write(Properties.Resources.LeftImagepng, 0, Properties.Resources.LeftImagepng.Length); zipOutputStream.CloseEntry(); } zipOutputStream.Close(); fileStream.Close(); //var newZipFile = ICSharpCode.SharpZipLib.Zip.ZipFile.Create("client.wyc"); //newZipFile.BeginUpdate(); //newZipFile.Add("iuclient.iuc"); //newZipFile.Add(new ICSharpCode.SharpZipLib.Zip.ZipEntry( //newZipFile.Add(Properties.Resources.HeaderImagepng, "HeaderImage.png"); //newZipFile.Add("LeftImage.png"); //newZipFile.CommitUpdate(); //newZipFile.Close(); } }
private static void Zip(string[] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream s) { List <string> rootPaths = new List <string>(); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = null; System.IO.FileStream fs = null; ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); try { ////创建当前文件夹 //entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("/"); //加上 “/” 才会当成是文件夹创建 //s.PutNextEntry(entry); //s.Flush(); foreach (string file in files) { if (System.IO.Directory.Exists(file)) { if (file.Split('\\').Count() > 1) { rootPaths.Add(file); entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Split('\\').Last() + "/"); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); } continue; } //打开压缩文件 fs = System.IO.File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); var zipfilename = System.IO.Path.GetFileName(file); foreach (var rootPath in rootPaths) { var _index = file.IndexOf(rootPath); if (_index >= 0) { zipfilename = rootPath.Split('\\').Last() + "\\" + System.IO.Path.GetFileName(file); break; } } entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipfilename) { DateTime = DateTime.Now, Size = fs.Length }; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); } }
} // End Sub WriteOdsFile private void SaveFromTemplate( ICSharpCode.SharpZipLib.Zip.ZipFile zipFile , ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOut , System.Xml.XmlDocument doc) { zipFile.IsStreamOwner = false; System.DateTime now = System.DateTime.Now; foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zipFile) { if (!zipEntry.IsFile) { continue; } string entryFileName = zipEntry.Name; // or Path.GetFileName(zipEntry.Name) to omit folder // Specify any other filtering here. using (System.IO.Stream zipStream = zipFile.GetInputStream(zipEntry)) { // Zips-within-zips are extracted. If you don't want this and wish to keep embedded zips as-is, just delete these 3 lines. //if (entryFileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { // RecursiveExtractRebuild(zipStream, _zipOut); //} //else { ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryFileName); newEntry.DateTime = now; // Setting the Size will allow the zip to be unpacked by XP's built-in extractor and other older code. // Mandatory newEntry.Size = zipEntry.Size; if (string.Equals(entryFileName, "content.xml", System.StringComparison.InvariantCultureIgnoreCase)) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { doc.Save(ms); newEntry.Size = ms.Length; // ms.Position = 0; ms.Seek(0, System.IO.SeekOrigin.Begin); zipOut.PutNextEntry(newEntry); ms.CopyTo(zipOut, 4096); zipOut.CloseEntry(); } // End Using ms } else { zipOut.PutNextEntry(newEntry); // StreamUtils.Copy(zipStream, zipOut, _buffer); zipStream.CopyTo(zipOut, 4096); zipOut.CloseEntry(); } } // End Using zipStream // } } // End Using zipEntry } // End Sub SaveFromTemplate