public void Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent() { var data = new byte[] { 1, 2, 3, 4 }; using (var stream = new MemoryStream()) { using (var zip = new ZipFile()) { zip.AddEntry(STR_TestBin, data); zip.Save(stream); } stream.Position = 0; using(var zip = ZipFile.Read(stream)) { using(var ms = new MemoryStream()) { zip[STR_TestBin].Extract(ms); var actual = ms.ToArray(); CollectionAssert.AreEquivalent(data, actual); } } } }
public void EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent() { var data = new byte[] { 1, 2, 3, 4 }; using (var stream = new MemoryStream()) { using (var zip = new ZipFile()) { zip.AddEntry(STR_TestBin, data); zip.Save(stream); stream.Position = 0; using (var fs = new FileStream(@"C:\Users\Ivan.z\Documents\test.bin.zip", FileMode.OpenOrCreate)) { fs.Position = 0; stream.WriteTo(fs); } } stream.Position = 0; using (var zip = ZipFile.Read(stream)) { using (var ms = new MemoryStream()) { zip[STR_TestBin].Extract(ms); var actual = ms.ToArray(); CollectionAssert.AreEquivalent(data, actual); } } } }
public static MemoryStream Compress(List <FileZip> lista) { MemoryStream retorno = new MemoryStream(); using (ZipFile zip = new ZipFile()) { foreach (var item in lista) { zip.AddEntry(item.Nome, item.Arquivo); } zip.Save(retorno); retorno.Seek(0, 0); } return(retorno); }
private void AddToZip(string name, byte[] data) { using (var file = new ZipFile(_zipFile)) { if (file.ContainsEntry(name)) { file.UpdateEntry(name, data); } else { file.AddEntry(name, data); } file.Save(); } }
static void WriteManifest(PassKit pk, ZipFile zipFile, Dictionary <string, string> manifestHashes, X509Certificate2 signingCertificate, X509Certificate2Collection chainCertificates) { var json = new JObject(); foreach (var key in manifestHashes.Keys) { json[key] = manifestHashes[key]; } var data = Encoding.UTF8.GetBytes(json.ToString()); zipFile.AddEntry("manifest.json", data); SignManifest(zipFile, data, signingCertificate, chainCertificates); }
public static byte[] GetZipFile(InvoiceInfo invoice) { byte[] bytes = invoice.Invoices.CreateBytes(); byte[] zipFileBinaryDataArray = null; using (MemoryStream memoryStreamOutput = new MemoryStream()) { using (ZipFile zip = new ZipFile()) { zip.AddEntry(invoice.Invoices.UUID.Value + ".XML", bytes); zip.Save(memoryStreamOutput); } zipFileBinaryDataArray = memoryStreamOutput.ToArray(); } return(zipFileBinaryDataArray); }
void WriteNameAndLore(ZipFile zipFile, IEnumerable <NameAndLore> list) { if (zipFile.ContainsEntry("names.txt")) { zipFile.RemoveEntry("names.txt"); } StringBuilder builder = new StringBuilder(); foreach (NameAndLore nameAndLore in list) { builder.AppendLine(nameAndLore.ToLine()); } zipFile.AddEntry("names.txt", builder.ToString(), Encoding.UTF8); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { TextFieldFonts example = new TextFieldFonts(); byte[] pdf1 = example.CreatePdf(false, false); byte[] pdf2 = example.CreatePdf(true, false); byte[] pdf3 = example.CreatePdf(false, true); zip.AddEntry(RESULT1, pdf1); zip.AddEntry(RESULT2, pdf2); zip.AddEntry(RESULT3, pdf3); zip.AddEntry(RESULT4, example.ManipulatePdf(pdf1)); zip.AddEntry(RESULT5, example.ManipulatePdf(pdf2)); zip.AddEntry(RESULT6, example.ManipulatePdf(pdf3)); zip.AddEntry(RESULT7, example.ManipulatePdfFont1(pdf3)); zip.AddEntry(RESULT8, example.ManipulatePdfFont2(pdf3)); zip.Save(stream); } }
private void DownloadAllZipped(int message_id, HttpContext context) { var mail_box_manager = new MailBoxManager(0); var attachments = mail_box_manager.GetMessageAttachments(TenantId, Username, message_id); if (attachments.Any()) { using (var zip = new ZipFile()) { zip.CompressionLevel = CompressionLevel.Level3; zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AlternateEncoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage); foreach (var attachment in attachments) { using (var file = AttachmentManager.GetAttachmentStream(attachment)) { var filename = file.FileName; if (zip.ContainsEntry(filename)) { var counter = 1; var temp_name = filename; while (zip.ContainsEntry(temp_name)) { temp_name = filename; var suffix = " (" + counter + ")"; temp_name = 0 < temp_name.IndexOf('.') ? temp_name.Insert(temp_name.LastIndexOf('.'), suffix) : temp_name + suffix; counter++; } filename = temp_name; } zip.AddEntry(filename, file.FileStream.GetCorrectBuffer()); } } context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(ArchiveName)); zip.Save(context.Response.OutputStream); } } }
/// <summary> /// Writes the <see cref="CDP4Common.SiteDirectoryData.SiteReferenceDataLibrary"/> to the <see cref="ZipFile"/> /// </summary> /// <param name="siteReferenceDataLibraries"> /// The <see cref="CDP4Common.SiteDirectoryData.SiteReferenceDataLibrary"/> that are to be written to the <see cref="ZipFile"/> /// </param> /// <param name="zipFile"> /// The target <see cref="ZipFile"/> that the <see cref="siteReferenceDataLibraries"/> are written to. /// </param> /// <param name="filePath"> /// The file of the target <see cref="ZipFile"/> /// </param> /// <param name="transaction"> /// The current transaction to the database. /// </param> /// <param name="authorizedContext"> /// The security context of the container instance. /// </param> /// <param name="partition"> /// The database partition (schema) where the requested resource is stored. /// </param> private void WriteSiteReferenceDataLibraryToZipFile( IEnumerable <SiteReferenceDataLibrary> siteReferenceDataLibraries, ZipFile zipFile, string filePath, NpgsqlTransaction transaction, RequestSecurityContext authorizedContext, string partition) { // Force deep get for reference data libraries var queryParameters = new QueryParameters { IncludeReferenceData = true, ExtentDeep = true }; this.RequestUtils.OverrideQueryParameters = queryParameters; foreach (var siteReferenceDataLibrary in siteReferenceDataLibraries) { var siteReferenceDataLibraryGuidList = new List <Guid>(); siteReferenceDataLibraryGuidList.Add(siteReferenceDataLibrary.Iid); // Get all siteRdl objects excluding siteRdl itself var dtos = this.SiteReferenceDataLibraryService .GetDeep(transaction, partition, siteReferenceDataLibraryGuidList, authorizedContext).ToList() .Where(x => x.ClassKind != ClassKind.SiteReferenceDataLibrary); // Serialize and save dtos to the archive using (var memoryStream = new MemoryStream()) { this.JsonSerializer.SerializeToStream(dtos, memoryStream); using (var outputStream = new MemoryStream(memoryStream.ToArray())) { var siteReferenceDataLibraryFilename = string.Format( "{0}\\{1}.json", SiteRdlZipLocation, siteReferenceDataLibrary.Iid); var zipEntry = zipFile.AddEntry(siteReferenceDataLibraryFilename, outputStream); zipEntry.Comment = string.Format( "The {0} SiteReferenceDataLibrary", siteReferenceDataLibrary.ShortName); zipFile.Save(filePath); } } } // Set query parameters back this.RequestUtils.OverrideQueryParameters = null; }
public void CreateApplcantCSV(DataTable App_Data) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.BufferOutput = false; HttpContext c = HttpContext.Current; string namedate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); string archiveName = "Export_CSV_" + namedate + ".zip"; HttpContext.Current.Response.ContentType = "application/zip"; HttpContext.Current.Response.AddHeader("content-disposition", "filename=" + archiveName); StringBuilder stringWrite = new StringBuilder(); stringWrite.Append("เลขที่สอบ,หมายเลขบัตรประชาชน,คำนำหน้า,ชื่อ,นามสกุล,วัน/เดือน/ปีเกิด,เพศ,วุฒิการศึกษา,รหัสบริษัท/สมาคม,ที่อยู่,รหัสพื้นที่,หน่วยรับสมัคร"); stringWrite.Append(Environment.NewLine); foreach (System.Data.DataRow rows in App_Data.Rows) { stringWrite.Append(rows["RUN_NO"].ToString() == null ? "" : rows["RUN_NO"].ToString() + ","); //เลขที่สอบ stringWrite.Append(rows["ID_CARD_NO"].ToString() == null ? "" : rows["ID_CARD_NO"].ToString() + ","); //หมายเลขบัตรประชาชน stringWrite.Append(rows["NAME"].ToString() == null ? "" : rows["NAME"].ToString() + ","); //คำนำหน้า stringWrite.Append(rows["NAMES"].ToString() == null ? "" : rows["NAMES"].ToString() + ","); //ชื่อ stringWrite.Append(rows["LASTNAME"].ToString() == null ? "" : rows["LASTNAME"].ToString() + ","); //นามสกุล stringWrite.Append(rows["BIRTH_DATE"].ToString() == null ? "" : rows["BIRTH_DATE"].ToString().Replace(" 0:00:00", "") + ","); //วัน/เดือน/ปีเกิด if (rows["SEX"].ToString() != null) { string sex = rows["SEX"].ToString() == "M" ? "ช," : "ญ,";//เพศ stringWrite.Append(sex); } //stringWrite.Append(rows["TESTING_NO"].ToString() == null ? "" : rows["TESTING_NO"].ToString() + ",");//รหัสสอบ //stringWrite.Append(rows["TESTING_DATE"].ToString() == null ? "" : rows["TESTING_DATE"].ToString().Replace(" 0:00:00", "") + ",");//วันที่สอบ //stringWrite.Append(rows["TEST_TIME_CODE"].ToString() == null ? "" : rows["TEST_TIME_CODE"].ToString() + ","); //รหัสเวลาสอบ stringWrite.Append(rows["EDUCATION_CODE"].ToString() == null ? "" : rows["EDUCATION_CODE"].ToString() + ","); //วุฒิการศึกษา stringWrite.Append(rows["INSUR_COMP_CODE"].ToString() == null ? "" : rows["INSUR_COMP_CODE"].ToString() + ","); //,รหัสบริษัท/สมาคม stringWrite.Append(rows["ADDRESS1"].ToString() == null ? "" : rows["ADDRESS1"].ToString() + ","); //ที่อยู่ stringWrite.Append(rows["AREA_CODE"].ToString() == null ? "" : rows["AREA_CODE"].ToString() + ","); //รหัสพื้นที่ stringWrite.Append(rows["UPLOAD_BY_SESSION"].ToString() == null ? "" : rows["UPLOAD_BY_SESSION"].ToString()); //หน่วยรับสมัคร stringWrite.Append(Environment.NewLine); } using (ZipFile zip = new ZipFile(System.Text.Encoding.UTF8)) { zip.AddEntry("FileImport_" + namedate + ".csv", stringWrite.ToString(), System.Text.Encoding.UTF8); zip.Save(HttpContext.Current.Response.OutputStream); } HttpContext.Current.Response.Close(); }
private static void WriteFile(object doc, string path) { try { XmlSerializer xmlSerializer = new XmlSerializer(doc.GetType()); using (MemoryStream strm = new MemoryStream()) { xmlSerializer.Serialize(strm, doc); strm.Position = 0; using (ZipFile zip = new ZipFile()) { zip.AddEntry("firmware.bin", strm); zip.Save(path); } } Logging.Log.Write("Файл сохранен - " + path); } catch { Logging.Log.Write("Ошибка сохранения файла - " + path); } }
protected void Page_Load(object sender, EventArgs e) { Response.AddHeader("Content-Type", "application/zip"); Response.AddHeader("Content-Disposition", "attachment; filename=\"mxp_" + MxpConstants.ProtocolMajorVersion + "_" + MxpConstants.ProtocolMinorVersion + "_reference_messages.zip\""); using (MemoryStream stream = new MemoryStream()) { using (ZipFile zip = new ZipFile()) { foreach (ReferenceMessage item in ReferenceMessageLoader.Current.ReferenceMessages.Values) { ZipEntry entry = zip.AddEntry(item.MessageFileName, "messages", item.ByteValue); } zip.Save(stream); } Response.OutputStream.Write(stream.GetBuffer(), 0, (int)stream.Length); } }
/// <summary> /// 压缩zip /// </summary> /// <param name="fileToZips">文件路径集合</param> /// <param name="zipedFile">想要压成zip的文件名</param> public void Zip(string[] fileToZips, string zipedFile) { using (ZipFile zip = new ZipFile(AppSettingHelper.Get <string>("ZipPath") + zipedFile + ".zip", Encoding.Default)) { foreach (string fileToZip in fileToZips) { using (FileStream fs = new FileStream(fileToZip, FileMode.Open, FileAccess.ReadWrite)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1); zip.AddEntry(fileName, buffer); } } zip.Save(); } }
/// <summary> /// Zipa uma coleção de arquivos em array de bytes. /// </summary> /// <param name="arquivos"></param> /// <returns></returns> public static byte[] Zip(Dictionary <string, byte[]> arquivos) { using (var zip = new ZipFile()) { zip.CompressionLevel = CompressionLevel.BestCompression; foreach (var a in arquivos) { zip.AddEntry(a.Key, a.Value); } using (var ms = new MemoryStream()) { zip.Save(ms); return(ms.ToArray()); } } }
public byte[] Save() { byte[] byteArray; using (ZipFile zip = new ZipFile()) { foreach (var file in files) { zip.AddEntry(file.Key, file.Value); } using (var memoryStream = new MemoryStream()) { zip.Save(memoryStream); byteArray = memoryStream.ToArray(); } } return(byteArray); }
public static void SerializeObjectToZip(object obj, string fileName, string zipName) { using (ZipFile zip = ZipFile.Read(gameDataLocation + CurrentSaveName + "/" + zipName + ".rzz")) using (Stream st = new MemoryStream()) { serializer.Serialize(st, obj); st.Position = 0; if (zip.ContainsEntry(fileName + ".rz")) { zip.UpdateEntry(fileName + ".rz", st); } else { zip.AddEntry(fileName + ".rz", st); } zip.Save(); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { zip.AddFile(PREFACE, ""); PdfReader reader = new PdfReader(PREFACE); PdfReaderContentParser parser = new PdfReaderContentParser(reader); StringBuilder sb = new StringBuilder(); ITextExtractionStrategy strategy; for (int i = 1; i <= reader.NumberOfPages; i++) { strategy = parser.ProcessContent(i, new SimpleTextExtractionStrategy()); sb.AppendLine(strategy.GetResultantText()); } zip.AddEntry(RESULT, sb.ToString()); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HelloWorldCompression hello = new HelloWorldCompression(); zip.AddEntry(RESULT1, hello.CreatePdf(-1)); byte[] compress0 = hello.CreatePdf(0); zip.AddEntry(RESULT2, compress0); zip.AddEntry(RESULT3, hello.CreatePdf(1)); zip.AddEntry(RESULT4, hello.CreatePdf(2)); zip.AddEntry(RESULT5, hello.CreatePdf(3)); byte[] compress6 = hello.CompressPdf(compress0); zip.AddEntry(RESULT6, compress6); zip.AddEntry(RESULT7, hello.DecompressPdf(compress6)); zip.Save(stream); } }
static void Pack(string[] args) { var prod = args.FirstOrDefault() == "prod"; var sourceFilesLocation = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), settings.DefaultFilesLocation)); var destArchiveFileName = GetIntermediateArchiveFullFileName(prod); if (File.Exists(destArchiveFileName)) { File.Delete(destArchiveFileName); Console.WriteLine("Deleting old {0}", destArchiveFileName); } Console.WriteLine("Creating {0}", destArchiveFileName); using (var zip = new ZipFile(destArchiveFileName)) { zip.ParallelDeflateThreshold = -1; // http://dotnetzip.codeplex.com/workitem/14087 Console.WriteLine("Reading files from {0}", sourceFilesLocation); var filesList = GetFilesList(sourceFilesLocation); if (!prod) { #if !MONOMAC filesList = filesList.Union(ResolveMasks(@"Formats\LogJoint - LogJoint debug trace.format.xml", sourceFilesLocation)); #endif } foreach (var relativeFilePath in filesList) { var sourceFileAbsolutePath = Path.Combine(sourceFilesLocation, relativeFilePath); var relativePathInArchive = Path.GetDirectoryName(relativeFilePath); if (string.Compare(relativeFilePath, settings.ConfigFileName, true) == 0) { var configDoc = MakeAppConfig(sourceFileAbsolutePath, prod); Console.WriteLine("Adding to archive: {0} (config modified to fetch {1} updates, {2} logging)", relativeFilePath, prod ? "prod" : "staging", prod ? "no" : "full"); zip.AddEntry(relativeFilePath, configDoc.ToString()); } else { Console.WriteLine("Adding to archive: {0}", relativeFilePath); zip.AddFile(sourceFileAbsolutePath, relativePathInArchive); } } zip.Save(); } Console.WriteLine("Successfully created: {0} ", destArchiveFileName); }
public static void ZipAFile(string zipFile, string entryName, string content, string comment) { if (string.IsNullOrWhiteSpace(zipFile)) { throw new ArgumentNullException(nameof(zipFile)); } if (string.IsNullOrWhiteSpace(entryName)) { throw new ArgumentNullException(nameof(entryName)); } if (string.IsNullOrWhiteSpace(content)) { throw new ArgumentNullException(nameof(content)); } if (!File.Exists(zipFile)) { using (var zip = new ZipFile()) { zip.AddEntry(entryName, File.ReadAllBytes(content)); zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; if (!string.IsNullOrWhiteSpace(comment)) { zip.Comment = comment; } zip.Save(zipFile); } } else { using (var zip = ZipFile.Read(zipFile)) { zip.AddEntry(entryName, File.ReadAllBytes(content)); if (!string.IsNullOrWhiteSpace(comment)) { zip.Comment = comment; } zip.Save(); } } }
/// <summary> /// Genera el ZIP del XML basandose en la trama del XML. /// </summary> /// <param name="tramaXml">Cadena Base64 con el contenido del XML</param> /// <param name="nombreArchivo">Nombre del archivo ZIP</param> /// <returns>Devuelve Cadena Base64 del archizo ZIP</returns> public string GenerarZip(string tramaXml, string nombreArchivo) { var memOrigen = new MemoryStream(Convert.FromBase64String(tramaXml)); var memDestino = new MemoryStream(); string resultado; using (var fileZip = new ZipFile(nombreArchivo + ".zip")) { fileZip.AddEntry(nombreArchivo + ".xml", memOrigen); fileZip.Save(memDestino); resultado = Convert.ToBase64String(memDestino.ToArray()); } // Liberamos memoria RAM. memOrigen.Close(); memDestino.Close(); return(resultado); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { ImageTypes it = new ImageTypes(); zip.AddEntry(RESULT, it.CreatePdf()); /* * uncomment if you want to see the image files in the zip archive; * some of them are semi-large files * * for (int i = 0; i < RESOURCES.Length; i++) { * zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCES[i]), ""); * } * zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCE), ""); */ zip.Save(stream); } }
protected virtual void WriteToFile(Map map, string filename, ZipFile mapFile) { var mapBaseFileName = map.MapName; mapFile.AddEntry(GetStaticFileName(), (name, f) => formatter.Serialize(f, map.StaticData)); mapFile.AddEntry(GetDynamicFileName(), (name, f) => formatter.Serialize(f, map.DynamicData)); foreach (var language in map.StringLocalizationStorage.GetLanguages()) { string fn = null; if (language == "en") { fn = "strings.resx"; } else { fn = "strings." + language + ".resx"; } mapFile.AddEntry(fn, (name, stream) => map.StringLocalizationStorage.WriteLanguageToStream(language, stream)); } mapFile.AddEntry(GetSettingsFileName(), (name, f) => formatter.Serialize(f, map.Settings)); if (map.Ground.SplatMap1 != null) { mapFile.AddEntry(GetSplatTexture1FileName(), (name, stream) => SlimDX.Direct3D9.BaseTexture.ToStream(map.Ground.SplatMap1.Resource9, SlimDX.Direct3D9.ImageFileFormat.Png).CopyTo(stream)); } if (map.Ground.SplatMap2 != null) { mapFile.AddEntry(GetSplatTexture2FileName(), (name, stream) => SlimDX.Direct3D9.BaseTexture.ToStream(map.Ground.SplatMap2.Resource9, SlimDX.Direct3D9.ImageFileFormat.Png).CopyTo(stream)); } mapFile.AddEntry(GetHeightmapFileName(), (name, stream) => SerializeHeightmap(map, stream)); }
//___________________________________________________________________________ private void ZipSql(string asOutput, string asFulllPathName) { using (ZipFile zip = new ZipFile()) { if (ChToMem.Checked) { string asFileName = Path.GetFileName(asFulllPathName); //Encoding Encdng = Encoding.Unicode; zip.AddEntry(asFileName, asOutput); } else { zip.AddFile(asFulllPathName); } //zip.AddFile (FilesToPack.ElementAt (iNumFl).Value.asNameFull, ""); //zip.AddFile (FilesToPack.ElementAt (iNumFl).Value.asName); zip.Save(asFulllPathName.Replace("sql", "zip")); //zip.Save (FilesToPack.ElementAt (iiNumFlValue.asName.Replace (asExtLog, "zip")); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { // Create a PdfCopyFields object PdfCopyFields copy = new PdfCopyFields(ms); // add a document copy.AddDocument(new PdfReader(DATASHEET)); // add a document copy.AddDocument(new PdfReader(DATASHEET)); // close the PdfCopyFields object copy.Close(); zip.AddEntry(RESULT, ms.ToArray()); } zip.AddFile(DATASHEET, ""); zip.Save(stream); } }
/// <summary> /// Add the contents of a memorystream as an entry in a .zip archive /// </summary> /// <param name="fullpath">the full path, including the .zip file extension</param> /// <param name="entryName">the full entry name, including possible file extensions</param> public static void AddItemToCompoundArchive(MemoryStream mStream, string fullpath, string entryName) { bool fileExists = File.Exists(fullpath); using (ZipFile zipFile = fileExists?new ZipFile(fullpath):new ZipFile()) { //serialize item to memorystream using (mStream) { if (zipFile.ContainsEntry(entryName)) { zipFile.RemoveEntry(entryName); } zipFile.AddEntry(entryName, mStream); zipFile.Save(fullpath); } } }
/// <summary> /// Writes bars to an entry in a zip file /// The zip file is always overwritten. /// </summary> /// <param name="zipFileName"></param> /// <param name="entryName"></param> /// <param name="sb"></param> private static void WriteZipFile(string zipFileName, string entryName, StringBuilder sb) { if (File.Exists(zipFileName)) { File.Delete(zipFileName); } using (var zip = new ZipFile(zipFileName)) { zip.AddEntry(entryName, sb.ToString()); zip.Save(); } if (_settings.EnableTrace) { Console.WriteLine("Created: " + zipFileName); } }
private Boolean Compress(string sqlfile) { using (ZipFile zip = new ZipFile(Encoding.GetEncoding("gb2312"))) { zip.Password = G_PASS; // 设置密码 zip.Encryption = G_ENCRYPT; // 添加版本受限和用户信息 ZipEntry e = zip.AddEntry(sqlfile, sb.ToString()); zip.Comment = user + "|" + cv.Product + "|" + cv.Sversion; // 获取输出文件名 zip.Save(file); } return(true); }
protected void BuildEpubStructure() { file = new ZipFile(); file.AddEntry("mimetype", Resources.Mimetype).CompressionLevel = CompressionLevel.None; if (!string.IsNullOrEmpty(Structure.Directories.ContentFolder)) { file.AddDirectoryByName(Structure.Directories.ContentFolder); } file.AddDirectoryByName(Structure.Directories.MetaInfFolder); if (!string.IsNullOrEmpty(Structure.Directories.ImageFolder)) { file.AddDirectoryByName(Structure.Directories.ImageFolderFullPath); } if (!string.IsNullOrEmpty(Structure.Directories.CssFolder)) { file.AddDirectoryByName(Structure.Directories.CssFolderFullPath); } }
private string SaveFiles(string Name, IEnumerable <HttpFileStream> Files) { string FileName = string.Empty; if (!Directory.Exists(UploadsFolderPath)) { Directory.CreateDirectory(UploadsFolderPath); } ZipFile zip = new ZipFile(); foreach (var File in Files) { zip.AddEntry(File.Name, File.InputStream); } FileName = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + Name.Replace(" ", "") + ".zip"; zip.Save(UploadsFolderPath + FileName); return(FileName); }
public byte[] GetCompressedEntityStream(IEntitySet[] entitySets) { using (var memoryStream = new MemoryStream()) using (ZipFile zip = new ZipFile()) { foreach (var entitySet in entitySets) { var type = entitySet.GetEntityType(); var entities = entitySet.GetEntities(); var key = type.FullName + ".json"; var data = JsonConvert.SerializeObject(entities); zip.AddEntry(key, data); } zip.Save(memoryStream); return(memoryStream.ToArray()); } }
public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZF() { // Verify that unsetting the Encryption property after // setting a Password results in no encryption being used. // This method tests ZipFile. string unusedPassword = TestUtilities.GenerateRandomPassword(); int numTotalEntries = _rnd.Next(46)+653; string zipFileToCreate = "UnsetEncryption.zip"; using (var zip = new ZipFile()) { zip.Password = unusedPassword; zip.Encryption = EncryptionAlgorithm.None; for (int i=0; i < numTotalEntries; i++) { if (_rnd.Next(7)==0) { string entryName = String.Format("{0:D5}", i); zip.AddDirectoryByName(entryName); } else { string entryName = String.Format("{0:D5}.txt", i); if (_rnd.Next(12)==0) { var block = TestUtilities.GenerateRandomAsciiString() + " "; string contentBuffer = String.Format("This is the content for entry {0}", i); int n = _rnd.Next(6) + 2; for (int j=0; j < n; j++) contentBuffer += block; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer); zip.AddEntry(entryName, contentBuffer); } else zip.AddEntry(entryName, Stream.Null); } } zip.Save(zipFileToCreate); } BasicVerifyZip(zipFileToCreate); }
public void CreateZip_AddEntry_String_BlankName() { string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddEntry_String_BlankName.zip"); using (ZipFile zip = new ZipFile()) { zip.AddEntry("", "This is the content."); zip.Save(zipFileToCreate); } }
public void Error_Save_InvalidLocation() { string badLocation = "c:\\Windows\\"; Assert.IsTrue(Directory.Exists(badLocation)); // Add an entry to the zipfile, then try saving to a directory. // This must fail. using (ZipFile zip = new ZipFile()) { zip.AddEntry("This is a file.txt", "Content for the file goes here."); zip.Save(badLocation); // fail } }
public void Error_NonZipFile_wi11743() { // try reading an empty, extant file as a zip file string zipFileToRead = Path.GetTempFileName(); _FilesToRemove.Add(zipFileToRead); using (ZipFile zip = new ZipFile(zipFileToRead)) { zip.AddEntry("EntryName1.txt", "This is the content"); zip.Save(); } }
public void Create_LargeSegmentedArchive() { // There was a claim that large archives (around or above // 1gb) did not work well with archive splitting. This test // covers that case. #if REMOTE_FILESYSTEM string parentDir = Path.Combine("t:\\tdir", Path.GetFileNameWithoutExtension(TopLevelDir)); _FilesToRemove.Add(parentDir); Directory.CreateDirectory(parentDir); string zipFileToCreate = Path.Combine(parentDir, "Create_LargeSegmentedArchive.zip"); #else string zipFileToCreate = Path.Combine(TopLevelDir, "Create_LargeSegmentedArchive.zip"); #endif TestContext.WriteLine("Creating file {0}", zipFileToCreate); // This file will "cache" the randomly generated text, so we // don't have to generate more than once. You know, for // speed. string cacheFile = Path.Combine(TopLevelDir, "cacheFile.txt"); // int maxSegSize = 4*1024*1024; // int sizeBase = 20 * 1024 * 1024; // int sizeRandom = 1 * 1024 * 1024; // int numFiles = 3; // int maxSegSize = 80*1024*1024; // int sizeBase = 320 * 1024 * 1024; // int sizeRandom = 20 * 1024 * 1024 ; // int numFiles = 5; int maxSegSize = 120*1024*1024; int sizeBase = 420 * 1024 * 1024; int sizeRandom = 20 * 1024 * 1024; int numFiles = _rnd.Next(5) + 11; TestContext.WriteLine("The zip will contain {0} files", numFiles); int numSaving= 0, totalToSave = 0, numSegs= 0; long sz = 0; // There are a bunch of Action<T>'s here. This test method originally // used ZipFile.AddEntry overload that accepts an opener/closer pair. // It conjured content for the files out of a RandomTextGenerator // stream. This worked, but was very very slow. So I took a new // approach to use a WriteDelegate, and still contrive the data, but // cache it for entries after the first one. This makes things go much // faster. // // But, when using the WriteDelegate, the SaveProgress events of // flavor ZipProgressEventType.Saving_EntryBytesRead do not get // called. Therefore the progress updates are done from within the // WriteDelegate itself. The SaveProgress events for SavingStarted, // BeforeWriteEntry, and AfterWriteEntry do get called. As a result // this method uses 2 delegates: one for writing and one for the // SaveProgress events. WriteDelegate writer = (name, stream) => { Stream input = null; Stream cache = null; try { // use a cahce file as the content. The entry // name will vary but we'll get the content for // each entry from the a single cache file. if (File.Exists(cacheFile)) { input = File.Open(cacheFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); // Make the file slightly shorter with each // successive entry, - just to shake things // up a little. Also seek forward a little. var fl = input.Length; input.SetLength(fl - _rnd.Next(sizeRandom/2) + 5201); input.Seek(_rnd.Next(sizeRandom/2), SeekOrigin.Begin); } else { sz = sizeBase + _rnd.Next(sizeRandom); input = new Ionic.Zip.Tests.Utilities.RandomTextInputStream((int)sz); cache = File.Create(cacheFile); } _txrx.Send(String.Format("pb 2 max {0}", sz)); _txrx.Send("pb 2 value 0"); var buffer = new byte[8192]; int n; Int64 totalWritten = 0; int nCycles = 0; using (input) { while ((n= input.Read(buffer,0, buffer.Length))>0) { stream.Write(buffer,0,n); if (cache!=null) cache.Write(buffer,0,n); totalWritten += n; // for performance, don't update the // progress monitor every time. nCycles++; if (nCycles % 312 == 0) { _txrx.Send(String.Format("pb 2 value {0}", totalWritten)); _txrx.Send(String.Format("status Saving entry {0}/{1} {2} :: {3}/{4}mb {5:N0}%", numSaving, totalToSave, name, totalWritten/(1024*1024), sz/(1024*1024), ((double)totalWritten) / (0.01 * sz))); } } } } finally { if (cache!=null) cache.Dispose(); } }; EventHandler<SaveProgressEventArgs> sp = (sender1, e1) => { switch (e1.EventType) { case ZipProgressEventType.Saving_Started: numSaving= 0; break; case ZipProgressEventType.Saving_BeforeWriteEntry: _txrx.Send("test Large Segmented Zip"); _txrx.Send(String.Format("status saving {0}", e1.CurrentEntry.FileName)); totalToSave = e1.EntriesTotal; numSaving++; break; // case ZipProgressEventType.Saving_EntryBytesRead: // if (!_pb2Set) // { // _txrx.Send(String.Format("pb 2 max {0}", e1.TotalBytesToTransfer)); // _pb2Set = true; // } // _txrx.Send(String.Format("status Saving entry {0}/{1} {2} :: {3}/{4}mb {5:N0}%", // numSaving, totalToSave, // e1.CurrentEntry.FileName, // e1.BytesTransferred/(1024*1024), e1.TotalBytesToTransfer/(1024*1024), // ((double)e1.BytesTransferred) / (0.01 * e1.TotalBytesToTransfer))); // string msg = String.Format("pb 2 value {0}", e1.BytesTransferred); // _txrx.Send(msg); // break; case ZipProgressEventType.Saving_AfterWriteEntry: TestContext.WriteLine("Saved entry {0}, {1} bytes", e1.CurrentEntry.FileName, e1.CurrentEntry.UncompressedSize); _txrx.Send("pb 1 step"); _pb2Set = false; break; } }; _txrx = TestUtilities.StartProgressMonitor("largesegmentedzip", "Large Segmented ZIP", "Creating files"); _txrx.Send("bars 3"); _txrx.Send("pb 0 max 2"); _txrx.Send(String.Format("pb 1 max {0}", numFiles)); // build a large zip file out of thin air var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.BufferSize = 256 * 1024; zip.CodecBufferSize = 128 * 1024; zip.MaxOutputSegmentSize = maxSegSize; zip.SaveProgress += sp; for (int i = 0; i < numFiles; i++) { string filename = TestUtilities.GetOneRandomUppercaseAsciiChar() + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".txt"; zip.AddEntry(filename, writer); } zip.Save(zipFileToCreate); numSegs = zip.NumberOfSegmentsForMostRecentSave; } #if REMOTE_FILESYSTEM if (((long)numSegs*maxSegSize) < (long)(1024*1024*1024L)) { _FilesToRemove.Remove(parentDir); Assert.IsTrue(false, "There were not enough segments in that zip. numsegs({0}) maxsize({1}).", numSegs, maxSegSize); } #endif _txrx.Send("status Verifying the zip ..."); _txrx.Send("pb 0 step"); _txrx.Send("pb 1 value 0"); _txrx.Send("pb 2 value 0"); ReadOptions options = new ReadOptions { StatusMessageWriter = new StringWriter() }; string extractDir = "verify"; int c = 0; while (Directory.Exists(extractDir + c)) c++; extractDir += c; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate, options)) { _numFilesToExtract = zip2.Entries.Count; _numExtracted= 1; _pb1Set= false; zip2.ExtractProgress += ExtractProgress; zip2.ExtractAll(extractDir); } string status = options.StatusMessageWriter.ToString(); TestContext.WriteLine("status:"); foreach (string line in status.Split('\n')) TestContext.WriteLine(line); }