private static void CreateArchive(IEnumerable <JobInfo> jobs, string archiveFile) { File.Delete(archiveFile); var zipper = new ZipFile(archiveFile); zipper.AddFiles(jobs.Select(it => it.ImageFile)); zipper.Save(); }
private static void ZipRecords(DirectoryInfo directory) { using (ZipFile zip = new ZipFile()) { zip.AddFiles(directory.GetFiles().Select(s => s.FullName), String.Empty); zip.Save(String.Format("{0}\\lei sample ({1}).zip", directory.FullName, RecordsCount)); Console.WriteLine("Created zip file: lei sample ({0}).zip", RecordsCount); } }
/// ------------------------------------------------------------------------------------ protected override void PerformZipWork(ZipFile zip) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; zip.SaveProgress += HandleZipSaveProgress; zip.AddFile(_infoFile, string.Empty); zip.AddFiles(_prjFiles, string.Empty); if (_dataSourceFiles.Count > 0) { zip.AddFiles(_dataSourceFiles, "Data"); } if (_audioFiles.Count > 0) { zip.AddFiles(_audioFiles, "Audio"); } zip.Save(Path.Combine(GetBackupDestinationFolder(), BackupFile)); }
public static void Compress(string[] filePath, string savePath) { using (ZipFile file = new ZipFile()) { foreach (string path in filePath) { file.AddFiles(filePath); file.Save(savePath); } } }
void saveZip(string prefix, string sourcedir, string targetdir) { string zipname = Path.ChangeExtension(prefix, ".zip"); string[] files = Directory.GetFiles(sourcedir); using (ZipFile zip = new ZipFile()) { zip.AddFiles(files, ""); zip.Save(Path.Combine(targetdir, zipname)); } }
/// <summary> /// 创建压缩包 /// </summary> /// <param name="files"></param> /// <param name="zipPath"></param> public static void CreateZip(IEnumerable <string> files, string zipPath) { //ZipFile实例化一个对象zip using (ZipFile zip = new ZipFile(Encoding.Default)) { //加密压缩 //zip.Password = "******"; zip.AddFiles(files); zip.Save(zipPath); } }
public override void ExecuteResult(ControllerContext context) { using (ZipFile zf = new ZipFile()) { zf.AddFiles(_files, false, ""); context.HttpContext .Response.ContentType = "application/zip"; context.HttpContext .Response.AppendHeader("content-disposition", "attachment; filename=" + FileName); zf.Save(context.HttpContext.Response.OutputStream); } }
public static void CreatePackagedFile(string packagedFileName, params string[] files) { using (ZipFile zip = new ZipFile(packagedFileName)) { zip.AddFiles(files, false, ""); zip.Save(); foreach (var file in files) { File.Delete(file); } } }
private static void CompressTheIndex(string zipFilePath, string backupDirectoryPath) { using (ZipFile zip = new ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; Progress.StartCompressTheIndex(); String[] filenames = System.IO.Directory.GetFiles(backupDirectoryPath); zip.AddFiles(filenames, COMPRESSIONROOT); zip.Save(zipFilePath); Progress.FinishCompressTheIndex(); } }
/// <summary> /// Добалвяет файлы в архив. /// </summary> /// <param name="Path"></param> /// <param name="Files"></param> /// <param name="DirectoryPathInArchive"></param> public static void AddFiles(String Path, String[] Files, String DirectoryPathInArchive) { ZipFile Archive = new ZipFile(Path) { CompressionLevel = CompressionLevel.BestCompression }; Archive.AddFiles(Files, DirectoryPathInArchive); Archive.Save(Path); Archive.Dispose(); }
public void ProcessRequest(HttpContext context) { using (var zip = new ZipFile()) { zip.AddDirectory(HttpContext.Current.Server.MapPath(Multilingual.Multilingual.TranslationFilesRelativePath), "Translations"); zip.AddFiles(Template.Template.Templates.Select(el => el.Value), true, "Templates"); zip.Save(context.Response.OutputStream); } context.Response.ContentType = "application/zip"; context.Response.AddHeader("content-disposition", "attachment; filename=AppData.zip"); context.Response.Flush(); }
private byte[] CreateContentBytes(IEnumerable <string> paths) { using (var outputStream = new MemoryStream()) { using (var zip = new ZipFile()) { zip.AddFiles(paths, false, ""); zip.Save(outputStream); } return(outputStream.ToArray()); } }
internal Optional <World> LoadFromFile(string saveDir) { if (!Directory.Exists(saveDir) || !File.Exists(Path.Combine(saveDir, "Version" + fileEnding))) { Log.Warn("No previous save file found - creating a new one."); return(Optional.Empty); } try { PersistedWorldData persistedData = new PersistedWorldData(); SaveFileVersion saveFileVersion = SaveDataSerializer.Deserialize <SaveFileVersion>(Path.Combine(saveDir, "Version" + fileEnding)); if (saveFileVersion == null || saveFileVersion.Version != NitroxEnvironment.Version) { throw new InvalidDataException("Version file is empty or save data files are too old"); } persistedData.BaseData = SaveDataSerializer.Deserialize <BaseData>(Path.Combine(saveDir, "BaseData" + fileEnding)); persistedData.PlayerData = SaveDataSerializer.Deserialize <PlayerData>(Path.Combine(saveDir, "PlayerData" + fileEnding)); persistedData.WorldData = SaveDataSerializer.Deserialize <WorldData>(Path.Combine(saveDir, "WorldData" + fileEnding)); persistedData.EntityData = SaveDataSerializer.Deserialize <EntityData>(Path.Combine(saveDir, "EntityData" + fileEnding)); if (!persistedData.IsValid()) { throw new InvalidDataException("Save files are not valid"); } World world = CreateWorld(persistedData, config.GameMode); return(Optional.Of(world)); } catch (Exception ex) { //Backup world if loading fails using (ZipFile zipFile = new ZipFile()) { string[] nitroxFiles = Directory.GetFiles(saveDir, "*" + fileEnding); zipFile.AddFiles(nitroxFiles); zipFile.Save(Path.Combine(saveDir, "worldBackup.zip")); } #if DEBUG Log.Error($"Could not load world, creating a new one: {ex}"); #else Log.Warn($"Could not load world, creating a new one"); #endif } return(Optional.Empty); }
static void Main(string[] args) { using (ZipFile zip = new ZipFile()) { string[] files = Directory.GetFiles(@"."); files = (from o in files where !o.Contains(".z") && !o.Contains("zip.exe") select o).ToArray(); zip.AddFiles(files); zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G"); zip.MaxOutputSegmentSize = 99 * 1024 * 1024; // 2mb zip.Save("zip.zip"); //Console.ReadLine(); } }
public static string ZipLogFiles(List <string> logFilesPaths, string outputFolderPath = @"ArchivedIISLogs", string corporateName = "test") { string restulPath; using (ZipFile zip = new ZipFile()) { zip.AddFiles(logFilesPaths, ""); string zipFileName = corporateName + "-Hourly [" + DateTime.Now.ToString("yyyyMMddH") + "].zip"; restulPath = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), outputFolderPath, zipFileName)); zip.Save(restulPath); } return(restulPath); }
protected override void OnDoWork(object sender, DoWorkEventArgs e) { FileEx.Delete(this._zipPath); using (ZipFile zipFiles = new ZipFile(this._zipPath)) { zipFiles.AddFiles( from f in this._modPack.Files select f.FilePath, string.Empty); zipFiles.CompressionLevel = CompressionLevel.BestCompression; zipFiles.SaveProgress += new EventHandler <SaveProgressEventArgs>(this.SaveProgress); zipFiles.Save(this._zipPath); } }
/// <summary> /// 向zip文件内添加文件 /// </summary> /// <param name="FilePath">zip文件路径</param> /// <param name="AddFilePath">要添加的文件路径集合</param> /// <returns></returns> public string AddFile(string FilePath, string[] AddFilePath) { try { ZipFile zipfile = ZipFile.Read(FilePath); zipfile.AddFiles(AddFilePath); zipfile.Save(); } catch (Exception ex) { return(ex.ToString()); } return(null); }
protected void btnDownload_Click(object sender, EventArgs e) { int counter = 0; bool isSelected = false; List <string> filesToInclude = new List <string>(); foreach (GridDataItem item in radGridEntry.Items) { CheckBox chkbox = (CheckBox)item.FindControl("chkbox"); if (chkbox.Checked) { Entry entry = Entry.GetEntry(new Guid(item["Id"].Text)); entry.IsVideoDownloaded = true; entry.Save(); filesToInclude.Add(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"] + "EntryUpload\\CreativeVideo\\" + entry.Serial + "_CreativeMaterials_Video.mp4"); isSelected = true; counter++; } chkbox.Checked = false; // unchecked it } if (!isSelected) { lblError.Text = "Select at least 1 entry to downlaod video."; } else { string archiveName = String.Format("CreativeVideos-{0}.zip", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=\"" + archiveName + "\""); Response.ContentType = "application/zip"; Response.BufferOutput = true; using (ZipFile zip = new ZipFile()) { // filesToInclude is a string[] or List<String> zip.AddFiles(filesToInclude, "files"); zip.Save(Response.OutputStream); } lblError.Text = "Downloaded video for " + counter + " entry(s)."; Response.Redirect(Request.Url.GetLeftPart(UriPartial.Path).ToString()); } }
public OneOrZeroElementCollection <FileInfo> Compress(IEnumerable <FileInfo> filesToCompress, FileInfo compressedFileName) { if (filesToCompress == null) { throw new ArgumentNullException(nameof(filesToCompress)); } if (compressedFileName == null) { throw new ArgumentNullException(nameof(compressedFileName)); } if (!Directory.Exists(compressedFileName.Directory.FullName)) { throw new DirectoryNotFoundException(compressedFileName.Directory.FullName); } IList <FileInfo> filesList = filesToCompress.ToList(); if (!filesList.Any()) { return(new OneOrZeroElementCollection <FileInfo>()); } Array.ForEach(filesList.ToArray(), f => f.ThrowExceptionIfNullOrDoesntExists()); compressedFileName.ThrowExceptionIfExtensionIsDifferentFrom(Constants.FileExtensions.Zip); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (ZipFile zip = new ZipFile(compressedFileName.FullName)) { IEnumerable <string> filestoZip = filesList.Select(f => f.FullName); zip.AddFiles(filestoZip, string.Empty); Array.ForEach(zip.Entries.ToArray(), d => { d.Password = _password; d.CompressionLevel = _compressionLevel; //todo: I cannot extract file encrypted with AES256 d.Encryption = EncryptionAlgorithm.Zip20; } ); zip.Save(); } return(new OneOrZeroElementCollection <FileInfo>(compressedFileName)); }
/// <summary> /// 加入多個檔案至壓縮檔裡面 /// </summary> /// <param name="zipFilePathList">要壓縮的檔案資料集</param> /// <param name="zipSavaPath">壓縮檔路徑含檔名、副檔名</param> /// <param name="zipFolderName">壓縮後裡面的資料夾名稱,可以傳空字串</param> /// <param name="password">解壓縮密碼</param> /// <returns></returns> public static ZipExecuteResult ZipMultipleFileToZip(IEnumerable <string> zipFilePathList, string zipSavaPath, string zipFolderName = "", string password = null) { try { foreach (var item in zipFilePathList) { if (!File.Exists(item)) { return(ZipExecuteResult.Fail(string.Format("來源路徑:{0} 找不到該檔案。", item))); } } //原本壓縮檔存在的話就將其移除 if (!File.Exists(zipSavaPath)) { return(ZipExecuteResult.Fail("來源壓縮檔案路徑找不到該檔案。")); } using (ZipFile zip = ZipFile.Read(zipSavaPath)) { zip.Password = password; zip.UseZip64WhenSaving = Zip64Option.AsNecessary; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; foreach (var item in zip.EntryFileNames) { foreach (var fileNameItem in zipFilePathList) { if (Path.Combine(item.Split('/')) == Path.Combine(fileNameItem.Split('/'))) { return(ZipExecuteResult.Fail("檔案已存在")); } } } zip.AddFiles(zipFilePathList, zipFolderName); zip.Save(zipSavaPath); return(ZipExecuteResult.Ok()); } } catch (Exception ex) { return(ZipExecuteResult.Fail(ex.ToString())); } }
private void _Internal_ExtractExisting(int flavor) { string ZipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor)); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); var filenames = Directory.GetFiles(resourceDir); using (ZipFile zip = new ZipFile(ZipFileToCreate)) { zip.AddFiles(filenames, ""); zip.Comment = "This is a Comment On the Archive"; zip.Save(); } Assert.AreEqual <int>(TestUtilities.CountEntries(ZipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); // Extract twice: the first time should succeed. // The second, should fail, because of a failed file overwrite. // Unless flavor==3, in which case we overwrite silently. for (int k = 0; k < 2; k++) { using (ZipFile zip = ZipFile.Read(ZipFileToCreate)) { if (flavor > 10) { zip.ExtractProgress += OverwriteDecider; } for (int j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; if (flavor == 4) { e.Extract("unpack"); } else { e.Extract("unpack", (ExtractExistingFileAction)flavor); } } } } }
/// <summary> /// Compresses all the files in the specified top directory. Directory structure is not kept. /// Main purpose is to pack the TrafficViewer file data /// </summary> /// <param name="sourceDirectory"></param> /// <param name="targetArchivePath"></param> public static void CompressFiles(string sourceDirectory, string targetArchivePath) { try { using (ZipFile zip = new ZipFile()) { string[] files = Directory.GetFiles(sourceDirectory); zip.AddFiles(files, false, String.Empty); zip.Save(targetArchivePath); } } catch (Exception ex) { SdkSettings.Instance.Logger.Log(TraceLevel.Error, "Cannot compress files: {0}", ex.Message); } }
public static string ZipFile(string path, string[] files) {//, string userName, string password) { //SafeTokenHandle safeTokenHandel = CreateAuthenticationToken(userName, password); string zipFileName = string.Format("{0}{1}", path, "\\TestZipFile.zip"); //if (safeTokenHandel != null) { //WindowsIdentity id = new WindowsIdentity(safeTokenHandel.DangerousGetHandle()); using (ZipFile zipFile = new ZipFile(path)) { zipFile.AddFiles(files, false, string.Empty); zipFile.Save(path + "\\TestZipFile.zip"); zipFile.Dispose(); } //} return(zipFileName); }
private void ZipProject(List <string> files) { var existingFileFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files.zip"); if (File.Exists(existingFileFullPath)) { File.Delete(existingFileFullPath); } using (ZipFile zip = new ZipFile()) { zip.AddFiles(files); zip.Save("files.zip"); } }
private void ZipAllFiles(string ScratchDirectory, string _filename) { if (File.Exists(_filename)) { File.Delete(_filename); } using (var zip = new ZipFile(_filename)) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; var files = Directory.EnumerateFiles(ScratchDirectory); zip.AddFiles(files, ""); zip.Save(); } }
private void exportDoc(string jsonData) { var data = JsonConvert.DeserializeObject <List <JsonData> >(jsonData); Nuce_CTSV.updateStudentList(data); List <string> dirs = new List <string>(); foreach (var item in data) { string dir = print(item.ID.ToString(), false); dirs.Add(dir.Replace("~", "")); //dirs.Add(dir); } // Create destination document. //ComponentInfo.SetLicense("FREE-LIMITED-KEY"); //var destination = new DocumentModel(); //// Merge multiple source documents by importing their content at the end. //foreach (var fileDir in dirs) //{ // var source = DocumentModel.Load(fileDir); // destination.Content.End.InsertRange(source.Content); //} //// Save joined documents into one file. //destination.Save(Response, "Merged Files.docx"); string zipName = ""; using (ZipFile zipFile = new ZipFile()) { zipFile.AddFiles(dirs, false, ""); zipName = Server.MapPath("NuceDataUpload/Templates/xac_nhan_" + DateTime.Now.ToFileTime() + ".zip"); zipFile.Save(zipName); } foreach (var dir in dirs) { File.Delete(dir); } Response.Clear(); Response.Buffer = true; Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "attachment;filename=xac_nhan_" + DateTime.Now.ToFileTime() + ".zip"); Response.WriteFile(zipName); Response.Flush(); Response.Close(); File.Delete(zipName); }
//public static string[] ZipFileDLR(string downloadpath,string downloadurl,string _username) //{ // ZipFile zip=new ZipFile(); // string[] file = null; // DirectoryInfo dir = new DirectoryInfo(downloadpath); // FileInfo[] fileinf = dir.GetFiles(); // List<string> list = new List<string>(); // if ((fileinf != null) && (fileinf.Length > 0)) // { // foreach (FileInfo files in fileinf) // { // if (files.Name.EndsWith(".xls")) // { // list.Add(files.FullName); // } // } // zip.AddFiles(list, _username); // zip.Save(downloadpath + _username + ".zip"); // for (int i = 0; i < list.Count; i++) // { // File.Delete(list[i]); // } // FileInfo f = new FileInfo(downloadpath + _username + ".zip"); // file = new string[3]; // file[0] = f.Name; // file[1] = downloadurl + f.Name; // if (f.Length > (1024 * 1024)) // { // float fl = ((float)(f.Length) / (float)(1024 * 1024)); // file[2] = Math.Round(fl, MidpointRounding.ToEven).ToString() + "MB"; // } // else // { // float fl = ((float)(f.Length) / (float)(1024)); // file[2] = Math.Round(fl, MidpointRounding.ToEven).ToString() + "KB"; // } // return file; // } // else // { // return null; // } //} public static string[] ZipFileDLR(string downloadpath, string downloadurl, string _username) { ZipFile zip = new ZipFile(); string[] file = null; DirectoryInfo dir = new DirectoryInfo(downloadpath); FileInfo[] fileinf = dir.GetFiles(); List <string> list = new List <string>(); if ((fileinf != null) && (fileinf.Length > 0)) { foreach (FileInfo files in fileinf) { if (files.Name.EndsWith(".csv")) { list.Add(files.FullName); } } zip.AddFiles(list, _username); zip.Save(downloadpath + _username + ".zip"); for (int i = 0; i < list.Count; i++) { File.Delete(list[i]); } FileInfo f = new FileInfo(downloadpath + _username + ".zip"); file = new string[3]; file[0] = f.Name; file[1] = downloadurl + f.Name; if (f.Length > (1024 * 1024)) { float fl = ((float)(f.Length) / (float)(1024 * 1024)); file[2] = Math.Round(fl, MidpointRounding.ToEven).ToString() + "MB"; } else { float fl = ((float)(f.Length) / (float)(1024)); file[2] = Math.Round(fl, MidpointRounding.ToEven).ToString() + "KB"; } return(file); } else { return(null); } }
static void Main(string[] args) { string myZip = @"C:\temp\test.zip"; string myOtherZip = @"C:\temp\anotherZip.zip"; string outputDirectory = @"C:\ZipTest"; using (ZipFile zip = ZipFile.Read(myZip)) { zip.ExtractAll(outputDirectory, ExtractExistingFileAction.OverwriteSilently); } using (ZipFile zipDest = ZipFile.Read(myOtherZip)) { //zipDest.AddFiles(System.IO.Directory.EnumerateFiles(outputDirectory)); //This will add them as a directory zipDest.AddFiles((System.IO.Directory.EnumerateFiles(outputDirectory)), false, ""); //This will add the files to the root zipDest.Save(); } }
public bool CrearZip(string pathDestino, IList <string> pathsArchivos) { bool zipped = false; if (pathsArchivos.Count > 0) { using (var loanZip = new ZipFile()) { //var filePath = Path.Combine() loanZip.AddFiles(pathsArchivos, false, ""); loanZip.Save(pathDestino); zipped = true; } } return(zipped); }
[Timeout(5 * 60 * 1000)] // to protect against stuck file locks public void Spanned_InfoZip_Unzip_wi13691() { if (!InfoZipIsPresent) { throw new Exception("InfoZip is not present"); } TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List <String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // Save as segmented, then read/extract with winzip unzip // for various segment sizes. for (int k = 0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave." + k + ".zip"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); using (var zip1 = new ZipFile()) { zip1.AddFiles(filesToAdd, ""); zip1.MaxOutputSegmentSize = segSizes[k] * 1024; zip1.Save(zipFile1); } TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir, "extract"); Directory.CreateDirectory(extractDir); string args = String.Format("{0} -d {1}", zipFile1, extractDir); this.Exec(infoZipUnzip, args); string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted, trail {0}", k); } }
public void Spanned_Resave_Resave() { TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List<String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // for various segment sizes for (int k = 0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave." + k + ".zip"); string zipFile2 = Path.Combine(trialDir, "Updated." + k + ".zip"); string zipFile3 = Path.Combine(trialDir, "Again." + k + ".zip"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); using (var zip1 = new ZipFile()) { zip1.AddFiles(filesToAdd, ""); zip1.MaxOutputSegmentSize = segSizes[k] * 1024; zip1.Save(zipFile1); } TestContext.WriteLine(""); TestContext.WriteLine("Re-saving..."); using (var zip2 = FileSystemZip.Read(zipFile1)) { zip2.MaxOutputSegmentSize = segSizes[k] * 1024; zip2.Save(zipFile2); } TestContext.WriteLine(""); TestContext.WriteLine("Deleting initial archive..."); string[] filesToDelete = Directory.GetFiles(trialDir, "InitialSave.*"); foreach (var file in filesToDelete) { File.Delete(file); } TestContext.WriteLine(""); TestContext.WriteLine("Re-saving again..."); using (var zip3 = FileSystemZip.Read(zipFile2)) { zip3.MaxOutputSegmentSize = segSizes[k] * 1024; zip3.Save(zipFile3); } TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir, "extract"); Directory.CreateDirectory(extractDir); using (var zip4 = FileSystemZip.Read(zipFile3)) { foreach (var e in zip4) { TestContext.WriteLine(" {0}", e.FileName); e.Extract(extractDir); } } string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual<int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted."); } }
public void SilentDeletion_wi10639() { string zipFileToCreate = "SilentDeletion.zip"; string dirToZip = "dirToZip"; string extractDir = "extracted"; string password = TestUtilities.GenerateRandomPassword(); string wrongPassword = "******"; var files = TestUtilities.GenerateFilesFlat(dirToZip); TestContext.WriteLine("Creating the zip."); using (var zip = new ZipFile()) { zip.Password = password; zip.AddFiles(files, dirToZip); zip.Save(zipFileToCreate); } TestContext.WriteLine("Extract one file with wrong password."); // pick a random entry to extract int ix = -1; string extractedFile = null; // perform two passes: first with correct password to extract the // file. 2nd with incorrect password to see if the file is // deleted. Directory.CreateDirectory(extractDir); for (int i=0; i < 2; i++) { try { using (var zip = ZipFile.Read(zipFileToCreate)) { if (i==0) { do { ix = this._rnd.Next(zip.Entries.Count); } while (zip[ix].IsDirectory); TestContext.WriteLine("Selected entry: {0}", zip[ix].FileName); extractedFile = Path.Combine(extractDir, zip[ix].FileName.Replace("/","\\")); TestContext.WriteLine("name for extracted file: {0}", extractedFile); Assert.IsFalse(File.Exists(extractedFile), "The file exists."); } TestContext.WriteLine("Cycle {0}: ExtractWithPassword()", i); zip[ix].ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, (i==0)? password : wrongPassword); } } catch (BadPasswordException) { // only swallow exceptions on the first go-round if (i==0) throw; } Assert.IsTrue(File.Exists(extractedFile), "Cycle {0}: The extracted file does not exist.", i); } }
public void Password_CheckZipPassword_wi13664() { string[] passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "_" }; string dirToZip = Path.Combine(TopLevelDir, "zipthis"); int subdirCount; int entries = TestUtilities.GenerateFilesOneLevelDeep (TestContext, "wi13664", dirToZip, null, out subdirCount); string[] filesToZip = Directory.GetFiles("zipthis", "*.*", SearchOption.AllDirectories); Assert.AreEqual<int>(filesToZip.Length, entries, "Incorrect number of entries in the directory."); for (int j = 0; j < passwords.Length; j++) { string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_CheckZipPassword_wi13664-{0}.zip", j)); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { zip1.Password = passwords[j]; zip1.AddFiles(filesToZip, true, ""); zip1.Save(zipFileToCreate); } var r = ZipFile.CheckZipPassword(zipFileToCreate, passwords[j]); Assert.IsTrue(r, "Bad password in round {0}", j); } }
public void Error_AddFile_Twice() { int i; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_Twice.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "files"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(23) + 14; for (i = 0; i < numFilesToCreate; i++) TestUtilities.CreateUniqueFile("bin", subdir, _rnd.Next(10000) + 5000); // Create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { zip1.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); zip1.AddFiles(files, "files"); zip1.Save(); } // this should fail - adding the same file twice using (ZipFile zip2 = new ZipFile(zipFileToCreate)) { zip2.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); for (i = 0; i < files.Length; i++) zip2.AddFile(files[i], "files"); zip2.Save(); } }
private void _Internal_ExtractExisting(int flavor) { string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor)); string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Assert.IsTrue(Directory.Exists(resourceDir)); Directory.SetCurrentDirectory(TopLevelDir); var filenames = Directory.GetFiles(resourceDir); using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.AddFiles(filenames, ""); zip.Comment = "This is a Comment On the Archive"; zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); // Extract twice: the first time should succeed. // The second, should fail, because of a failed file overwrite. // Unless flavor==3, in which case we overwrite silently. for (int k = 0; k < 2; k++) { using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { if (flavor > 10) zip.ExtractProgress += OverwriteDecider; for (int j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; if (flavor == 4) e.Extract("unpack"); else e.Extract("unpack", (ExtractExistingFileAction) flavor); } } } }
[Timeout(5 * 60*1000)] // to protect against stuck file locks public void Spanned_InfoZip_Unzip_wi13691() { if (!InfoZipIsPresent) throw new Exception("InfoZip is not present"); TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List<String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // Save as segmented, then read/extract with winzip unzip // for various segment sizes. for (int k=0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave."+k+".zip"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); using (var zip1 = new ZipFile()) { zip1.AddFiles(filesToAdd, ""); zip1.MaxOutputSegmentSize = segSizes[k] * 1024; zip1.Save(zipFile1); } TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir,"extract"); Directory.CreateDirectory(extractDir); string args = String.Format("{0} -d {1}", zipFile1, extractDir); this.Exec(infoZipUnzip, args); string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual<int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted, trail {0}", k); } }
[Timeout(5 * 60*1000)] // to protect against stuck file locks public void Spanned_Resave_wi13915() { TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List<String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // Three passes: // pass 1: save as regular, then resave as segmented. // pass 2: save as segmented, then resave as regular. // pass 3: save as segmented, then resave as another segmented archive. for (int m=0; m < 3; m++) { // for various segment sizes for (int k=0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}.{1}", m, k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave."+m+"."+k+".zip"); string zipFile2 = Path.Combine(trialDir, "Updated."+m+"."+k+".zip"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0},{1})...{2}", m, k, DateTime.Now.ToString("G")); using (var zip1 = new ZipFile()) { zip1.AddFiles(filesToAdd, ""); if (m!=0) zip1.MaxOutputSegmentSize = segSizes[k] * 1024; zip1.Save(zipFile1); } TestContext.WriteLine(""); TestContext.WriteLine("Re-saving..."); using (var zip2 = ZipFile.Read(zipFile1)) { if (m==0) zip2.MaxOutputSegmentSize = segSizes[k] * 1024; else if (m==2) zip2.MaxOutputSegmentSize = 1024 * (3 * segSizes[k])/2; zip2.Save(zipFile2); } TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir,"extract"); Directory.CreateDirectory(extractDir); using (var zip3 = ZipFile.Read(zipFile2)) { foreach (var e in zip3) { TestContext.WriteLine(" {0}", e.FileName); e.Extract(extractDir); } } string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual<int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted."); } } }