public static void Compress(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.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> /// 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))) { 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> /// Exports the query results to an excel file per query. /// </summary> /// <param name="viewType">Indicates the type of response view.</param> /// <returns></returns> public Stream ExportAsExcel(TaskItemTypes viewType) { MemoryStream ms = new MemoryStream(); var includeDataMartName = viewType != TaskItemTypes.AggregateResponse; if (Queries.Count() > 1) { var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms); zipStream.IsStreamOwner = false; foreach (var grouping in Queries) { var datamartAcronym = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty; string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "xlsx"); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename); zipEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(zipEntry); WriteExcel(zipStream, grouping.AsEnumerable(), includeDataMartName); zipStream.CloseEntry(); } zipStream.Close(); } else { WriteExcel(ms, Queries.ElementAt(0).ToArray(), includeDataMartName); } ms.Position = 0; return(ms); }
public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) { MemoryStream outputMemStream = new MemoryStream(); var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outputMemStream); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); ICSharpCode.SharpZipLib.Core.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; }
/// <summary> /// Constrói um pacote com as dependencias informadas. /// </summary> /// <param name="outStream">Stream de saída.</param> /// <param name="entries"></param> /// <returns></returns> public static void BuildPackage(System.IO.Stream outStream, IEnumerator <Tuple <DataEntryVersion, System.IO.Stream> > entries) { outStream.Require("outStream").NotNull(); outStream.Require("entries").NotNull(); var buffer = new byte[1024]; int read = 0; var zipOut = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outStream); while (entries.MoveNext()) { var item = entries.Current; if (item == null) { continue; } var entryName = item.Item1.TypeName.FullName; var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName); entry.Size = item.Item2.Length; zipOut.PutNextEntry(entry); while ((read = item.Item2.Read(buffer, 0, buffer.Length)) > 0) { zipOut.Write(buffer, 0, read); } zipOut.CloseEntry(); } zipOut.Finish(); zipOut.Flush(); }
/// <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> /// Exports the responses in csv format, if the response is multi-query each query response will be a separate csv file zipped into a file of the request name. /// </summary> /// <param name="viewType">The response result view type, Individual or Aggregate.</param> /// <returns></returns> public Stream ExportAsCSV(TaskItemTypes viewType) { var queries = Queries.ToArray(); var includeDataMartName = viewType != TaskItemTypes.AggregateResponse; MemoryStream ms = new MemoryStream(); if (queries.Count() > 1) { var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms); zipStream.IsStreamOwner = false; foreach (var grouping in Queries) { var datamartAcronym = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty; string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "csv"); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename); zipEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(zipEntry); using (var writer = new StreamWriter(zipStream, System.Text.Encoding.Default, 1024, true)) { for (int i = 0; i < grouping.Count(); i++) { var responseResult = grouping.ElementAt(i); WriteCSV(writer, responseResult, i == 0, includeDataMartName); } writer.Flush(); zipStream.CloseEntry(); } } zipStream.Close(); } else { var firstQueryGrouping = Queries.ElementAt(0).ToArray(); using (var writer = new StreamWriter(ms, System.Text.Encoding.Default, 1024, true)) { for (int i = 0; i < firstQueryGrouping.Length; i++) { WriteCSV(writer, firstQueryGrouping[i], i == 0, includeDataMartName); } writer.Flush(); } } ms.Position = 0; return(ms); }
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; } }
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); } }
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); } }
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 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
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(); } }