private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); FolderBrowserDialog fbd = new FolderBrowserDialog(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { ZipFile zf = new ZipFile("C:\\Users\\cpaine\\Desktop\\MyZipFile.zip"); zf.AddDirectoryByName("Adam"); zf.AddFile(ofd.FileName, "Adam"); //zf.AddDirectory(fbd.SelectedPath, ""); if.Save; } }
public static void Export(IEnumerable <string> paths, Stream stream) { using (ZipFile zipFile = new ZipFile()) { foreach (var p in paths) { System.IO.DirectoryInfo di = new DirectoryInfo(p); if ((di.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { zipFile.AddDirectory(p, di.Name); } else { zipFile.AddFile(p, ""); } } zipFile.Save(stream); } }
public void Error_Save_NoFilename() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); string filename = Path.Combine(resourceDir, "TestStrings.txt"); Assert.IsTrue(File.Exists(filename), String.Format("The file '{0}' doesnot exist.", filename)); // add an entry to the zipfile, then try saving, never having specified a filename. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddFile(filename, ""); zip.Save(); // FAIL: don't know where to save! } // should never reach this Assert.IsTrue(false); }
private static string ArchiveLogFile(string logFilePath) { var directory = Path.GetDirectoryName(logFilePath); var fileName = Path.GetFileNameWithoutExtension(logFilePath); if (directory == null) { throw new InvalidOperationException("Log directory is null."); } var zipPath = Path.Combine(directory, $"{fileName}.zip"); using (var archive = new ZipFile()) { archive.AddProgress += ArchiveOnAddProgress; archive.SaveProgress += ArchiveOnSaveProgress; archive.AddFile(logFilePath, string.Empty); archive.Save(zipPath); } return(zipPath); }
public static void Compress(string folderPath, string fileName) { try { string extension = ".zip"; string file = folderPath + @"\" + fileName; fileName = (fileName + extension).Replace(".bak", ""); Thread thread = new Thread(t => { using (ZipFile zip = new ZipFile()) { zip.Password = "******"; zip.CompressionLevel = CompressionLevel.BestCompression; FileInfo fileInfo = new FileInfo(fileName); zip.AddFile(file, ""); DirectoryInfo di = new DirectoryInfo(file); folderPath = string.Format(@"{0}\{1}", di.Parent.FullName, fileInfo.Name); zip.Save(folderPath); File.Delete(file); var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = file; SHFileOperation(ref shf); Console.WriteLine("Compress completed."); } }); thread.Start(); } catch (Exception ex) { Console.WriteLine("Compress completed."); Console.WriteLine(ex.Message); } }
private async Task Compress() { using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.Always; zip.AlternateEncoding = Encoding.GetEncoding(866); foreach (ListViewItem item in currentListView.SelectedItems) { if (String.IsNullOrEmpty(item.SubItems[1].Text)) { continue; } string path = currentTextBox.Text + item.SubItems[0].Text + item.SubItems[1].Text; try { if (File.Exists(path)) { await Task.Run(() => zip.AddFile(path, "")); } else { await Task.Run(() => zip.AddDirectory(path, "")); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } ArchiveForm archiveForm; if (currentListView == listView1) { archiveForm = new ArchiveForm(zip, textBox1.Text); } else { archiveForm = new ArchiveForm(zip, textBox2.Text); } archiveForm.ShowDialog(); archiveForm.Dispose(); LoadInfo(listView1, textBox1); LoadInfo(listView2, textBox2); } }
public void Save() { FileStream fs = new FileStream(MyFilename, FileMode.Create, FileAccess.Write); byte[] buff; ZipFile zipin = new ZipFile(); foreach (SaveFileEntry ent in Files) { FileStream fs2 = new FileStream(ent.FileName, FileMode.Create, FileAccess.Write); fs2.Write(ent.memory.ToArray(), 0, (int)ent.memory.Length); fs2.Close(); if (File.Exists(ent.FileName)) { zipin.AddFile(ent.FileName); zipin.Save("temp.zip"); } File.Delete(ent.FileName); } zip = zipin; FileStream fs3 = new FileStream("temp.zip", FileMode.Open, FileAccess.Read); int len = (int)fs3.Length; buff = new byte[len]; fs3.Read(buff, 0, len); fs3.Close(); zipfile = new MemoryStream(buff); File.Delete("temp.zip"); MemoryStream m = new MemoryStream(); complete.Seek(8, SeekOrigin.Begin); int off = ReadInt(complete); complete.Seek(0, SeekOrigin.Begin); buff = new byte[off]; complete.Read(buff, 0, off); m.Write(buff, 0, off); m.Write(zipfile.ToArray(), 0, (int)zipfile.Length); fs.Write(m.ToArray(), 0, (int)m.Length); fs.Close(); }
public void UpdateZip() { if (IsActual()) { return; } using (var zip = new ZipFile()) { zip.CompressionLevel = CompressionLevel.BestSpeed; foreach (var f in EnumerateFiles()) { var newContent = getFileContent(f); if (newContent == null) { zip.AddFile(f.FullName, Path.GetDirectoryName(f.GetRelativePath(dir.FullName))); } else { zip.AddEntry( f.GetRelativePath(dir.FullName), _ => { newContent.Position = 0; return(newContent); }, (_, s) => s.Dispose() ); } } foreach (var fileToAdd in filesToAdd) { var directoriesList = GetDirectoriesList(fileToAdd.Path); if (!excludedDirs.Intersect(directoriesList).Any()) { zip.UpdateEntry(fileToAdd.Path, fileToAdd.Data); } } zip.Save(zipFile.FullName); } }
internal static string createBookArchived(int id) { var clientfiles = HttpContext.Current.Server.MapPath("~/upload/clientsfiles/"); var archive = HttpContext.Current.Server.MapPath("~/archived/library-archived-" + id + ".zip"); new Thread(() => { string apiUrl = ConfigurationManager.AppSettings["api"] + "odata/library/books/file/" + id; File.Delete(archive); object input = new { }; string inputJson = (new JavaScriptSerializer()).Serialize(input); //string inputJson = (new JavaScriptSerializer()).Serialize(input); WebClient client = new WebClient(); client.Headers["Content-type"] = "application/json"; client.Encoding = Encoding.UTF8; string json = client.UploadString(apiUrl, inputJson); var book = (new JavaScriptSerializer()).Deserialize <BookDto>(json); if (book.Files.Count > 0) { using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; // zip.AddDirectoryByName("Files"); foreach (var f in book.Files) { var fn = clientfiles + f; zip.AddFile(fn, book.Title.Replace(" ", "-").Replace("<", "-").Replace(">", "-").Replace(":", "-").Replace("/", "-").Replace("|", "-").Replace("*", "-").Replace("?", "-")); } zip.Save(archive); } } }).Start(); return(string.Empty); }
private void DownloadUserAttachments(String CommaSeperatedFiles) { string[] files = CommaSeperatedFiles.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //var archive = Server.MapPath("~/TaskAttachments/archive.zip"); //var temp = Server.MapPath("~/TaskAttachments/temp"); //// clear any existing archive //if (System.IO.File.Exists(archive)) //{ // System.IO.File.Delete(archive); //} //// empty the temp folder //Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f)); //// copy the selected files to the temp folder //foreach (var file in files) //{ // System.IO.File.Copy(file, Path.Combine(temp, Path.GetFileName(file))); //} //// create a new archive //ZipFile.CreateFromDirectory(temp, archive); using (ZipFile zip = new ZipFile()) { foreach (var file in files) { string filePath = Server.MapPath("~/TaskAttachments/" + file); zip.AddFile(filePath, "files"); } Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip"); Response.ContentType = "application/zip"; zip.Save(Response.OutputStream); Response.End(); } }
/// <summary> /// Build commit data file. /// </summary> /// <returns>The data file path.</returns> public string Build(string rootDir, string tempFile, Action <int> onProgress = null) { // delete the file when exists. if (File.Exists(tempFile)) { File.Delete(tempFile); } // compress all files using (var zip = new ZipFile(tempFile)) { zip.CompressionLevel = CompressionLevel.BestSpeed; zip.ParallelDeflateThreshold = -1; foreach (var file in Files) { if (file.DiffType == Filemap.FileDiff.Type.Delete) { continue; } var entry = zip.AddFile(rootDir + file.FileName); // add file // change name entry.FileName = file.FileName; } if (onProgress != null) { zip.SaveProgress += (sender, args) => { onProgress((int)((float)args.EntriesSaved / args.EntriesTotal * 100.0f)); }; } // save zip.Save(); } return(tempFile); }
/// <summary> /// It collect the uploadable files into param GDUploader variable and /// it collect the unnecessary files into global deletableFiles variable. /// </summary> /// <param name="uploader"></param> /// <param name="localFolder"></param> /// <param name="driveFolder"></param> private void CollectUpSynchronizerData(GDUploader uploader, string localFolder, IEnumerable <string> localFiles, string driveFolder) { foreach (string path in localFiles) { if (!exceptionLocalFiles.Contains(path) && path.StartsWith(localFolder)) { string currentDrivePath = driveFolder + path.Substring(localFolder.Length); if (Directory.Exists(path)) { CollectUpSynchronizerData(uploader, path, currentDrivePath); } else { string currentDriveFolder = currentDrivePath.Substring(0, currentDrivePath.LastIndexOf('\\')); string parentId = ConvertGDFolderToGDParentId(currentDriveFolder); string fileName = GetFileName(path); if (parentId != null) { string fileId = GetGDFileId(fileName + ".zip", parentId); if (fileId != null) { AddToDeletableFile(fileId); } } string zipFile = path + ".zip"; using (ZipFile zip = new ZipFile(zipFile)) { zip.Password = zipPassword; zip.AddFile(path, ""); zip.Save(); uploader.Add(new UploadableFile(zipFile, currentDriveFolder)); } } } } }
public string createPatch(string i_BaseCommonFolder, string i_Prod, string i_Build, string i_Description) { DateTime now = DateTime.Now; string timstamp = now.ToString(TIMESTAMP_FORMAT); string timstampPretty = now.ToString(TIMESTAMP_PRETTY_FORMAT); string archiveName = string.Format(FILENAME_FORMAT, m_ProjectName, i_Prod, i_Build, timstamp); string readmeName = string.Format(README_FORMAT, m_ProjectName, i_Prod, i_Build, timstamp); string userName = Environment.UserName; string machineName = Environment.MachineName; string readmeContent = string.Format(README_CONTENT_FORMAT, archiveName, m_ProjectName, i_Prod, i_Build, timstampPretty, userName, machineName, i_Description); string destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); using (ZipFile zip = new ZipFile()) { foreach (FilePath filePath in FilePaths) { int startIndex = filePath.Path.IndexOf("\\" + i_BaseCommonFolder + "\\"); int endIndex = filePath.Path.LastIndexOf("\\"); string path = filePath.Path.Substring(startIndex, endIndex - startIndex); string fileName = filePath.Path.Substring(endIndex + 1); if (File.Exists(filePath.Path)) { zip.AddFile(filePath.Path, path); readmeContent += string.Format("\n - {0}\\{1}", path, fileName); } } zip.AddEntry(readmeName, Encoding.UTF8.GetBytes(readmeContent)); zip.Save(archiveName); Directory.CreateDirectory(destinationFolder); if (!File.Exists(destinationFolder + "\\" + archiveName)) { File.Move(archiveName, destinationFolder + "\\" + archiveName); return(destinationFolder + "\\" + archiveName); } else { return(null); } } }
public void TestZipPackage() { /* * IMetrics metrics = new HP.TS.Devops.CentralConnect.Plugin.General.MetricsMockup(); * PluginResponse pluginResponse = metrics.GenerateMetrics(new MetricsRequest()); * System.Console.WriteLine(System.Text.Encoding.Default.GetString(pluginResponse.FileContent)); * */ Guid id = Guid.NewGuid(); string currentWorkFolder = System.IO.Path.Combine(workFolder, id.ToString()); if (!System.IO.Directory.Exists(currentWorkFolder)) { System.IO.Directory.CreateDirectory(currentWorkFolder); } //this.GenerateFiles(metricsRequest, currentWorkFolder); //HP.TS.Devops.CentralConnect.Plugin.Toolkits.Zip.GZip.Compress(@"D:\AAA", @"D:\", id.ToString()); string ZipFileToCreate = @"D:\" + id.ToString(); string DirectoryToZip = @"D:\AAA"; using (ZipFile zip = new ZipFile()) { // note: this does not recurse directories! String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip); // This is just a sample, provided to illustrate the DotNetZip interface. // This logic does not recurse through sub-directories. // If you are zipping up a directory, you may want to see the AddDirectory() method, // which operates recursively. foreach (String filename in filenames) { Console.WriteLine("Adding {0}...", filename); ZipEntry e = zip.AddFile(filename); e.Comment = "Added by Cheeso's CreateZip utility."; } zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'", System.Net.Dns.GetHostName()); zip.Save(ZipFileToCreate); } }
public static void generarZipConArchivoExcel(ExcelFileSpreadsheet spreadsheet) { DateTime date = DateTime.Now; String tempFolder = date.Date.ToString("yyyyMMdd") + date.Hour + date.Minute + date.Millisecond; String downloadPath = HttpContext.Current.Server.MapPath("~") + "\\downloads\\" + tempFolder; Directory.CreateDirectory(downloadPath); String fileName = "Descarga_" + date.Date.ToString("yyyyMMdd") + "_" + date.Hour + date.Minute + date.Millisecond; ExcelFileUtils.createExcelFile(spreadsheet, downloadPath, fileName); HttpContext context = HttpContext.Current; context.Response.Clear(); context.Response.ContentType = "application/zip"; context.Response.AddHeader("content-disposition", "filename=" + fileName + ".zip"); DirectoryInfo diFiles = new DirectoryInfo(downloadPath); using (ZipFile zip = new ZipFile()) { foreach (FileInfo fi in diFiles.GetFiles()) { zip.AddFile(downloadPath + "/" + fi.Name, ""); } zip.Save(context.Response.OutputStream); } // borrar archivos dentro del directorio virtual foreach (FileInfo file in diFiles.GetFiles()) { file.Delete(); } // borrar directorio virtual diFiles.Delete(true); context.Response.End(); }
private void CreateConfigBackup() { try { FileVersionInfo currentFv = FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PRoCon.exe")); FileVersionInfo updatedFv = FileVersionInfo.GetVersionInfo(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Updates"), "PRoCon.exe")); string zipFileName = String.Format("{0}_to_{1}_backup.zip", currentFv.FileVersion, updatedFv.FileVersion); using (ZipFile zip = new ZipFile()) { DirectoryInfo configsDirectory = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs")); FileInfo[] configFiles = configsDirectory.GetFiles("*.cfg"); foreach (FileInfo config in configFiles) { zip.AddFile(config.FullName, ""); } DirectoryInfo[] connectionConfigDirectories = configsDirectory.GetDirectories("*_*"); foreach (DirectoryInfo connectionConfigDirectory in connectionConfigDirectories) { zip.AddDirectory(connectionConfigDirectory.FullName, connectionConfigDirectory.Name); } if (Directory.Exists(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs"), "Backups")) == false) { Directory.CreateDirectory(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs"), "Backups")); } zip.Save(Path.Combine(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs"), "Backups"), zipFileName)); } this.Invoke(new StringParameterHandler(this.ConfigBackupSuccess), zipFileName); } catch (Exception e) { this.Invoke(new StringParameterHandler(this.ConfigBackupError), e.Message); } }
/// <summary> /// 创建一个 zip /// </summary> public string CreateZip(string path) { string logFail = ""; string logSuccess = ""; string zipPath = null; String[] filenames = System.IO.Directory.GetFiles(path); DataTable dt = excelData.Tables["table1"]; foreach (String filename in filenames) { String filenameWithoudPath = System.IO.Path.GetFileName(filename); using (ZipFile zip = new ZipFile()) { ZipEntry e = zip.AddFile(filename, ""); string studentNumber = filenameWithoudPath.Substring(fileNameNumberPosition, fileNameNuberLenth); string password = null; foreach (DataRow dr in dt.Rows) { string a = dr[0].ToString(); if (studentNumber.ToString() == dr[excelNumberPosition].ToString()) { //使用身份证号后6位加密 password = dr[excelIdNumberPosition].ToString().Substring(12, 6); break; } } if (password == null) { logFail += "学号为" + studentNumber + "的文件加密失败\n"; // Console.WriteLine(); continue; } e.Password = password; zipPath = Path.Combine(path, string.Format("{0}.zip", studentNumber)); zip.Save(zipPath); logSuccess += "学号为" + studentNumber + "的文件加密成功\n"; } } return(logFail + logSuccess); }
public ActionResult ProvvedimentoAiaRegionale(int id = 0) { ActionResult result = null; IEnumerable <DocumentoDownload> documenti = DocumentoRepository.Instance.RecuperaDocumentiDownloadPerProvvedimento(id); if (documenti.Count() > 0) { ZipFile zip = new ZipFile(); MemoryStream mss = new MemoryStream(); foreach (DocumentoDownload d in documenti) { string filepath = null; string ext = d.Estensione; filepath = FileUtility.VADocumentoAiaRegionale(string.Format("I{0}_P{1}/{2}.{3}", d.OggettoID, d.OggettoProceduraID, d.PercorsoFile, ext)); if (System.IO.File.Exists(filepath)) { zip.AddFile(filepath, ""); } } zip.Save(mss); zip.Dispose(); mss.Seek(0, SeekOrigin.Begin); result = File(mss, ContentTypeByExtension(".zip"), string.Format("P_{0}.zip", id)); if (!Request.Browser.Crawler) { new VAWebRequestDocumentoDownloadEvent("VA Download documento", this, id, VAWebEventTypeEnum.DownloadDocumentiProvvedimento).Raise(); } } else { result = HttpNotFound(); } return(result); }
protected void PackDown_Click(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=Homework.zip"); using (ZipFile zip = new ZipFile())//解决中文乱码问题 { foreach (GridViewRow gvr in GridView1.Rows) { if (((CheckBox)gvr.Cells[0].Controls[1]).Checked) { string m = Server.MapPath((gvr.Cells[3].Controls[1] as HyperLink).NavigateUrl); zip.AddFile(m, ""); } } zip.Save(Response.OutputStream); } //Response.End(); }
public static Error ZipFolder(string sourcePath, string outputZipFilename) { var error = new Error(); try { using (ZipFile zip = new ZipFile()) { string[] fileNames = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories); foreach (string file in fileNames) { string folderName = file.Replace(sourcePath, ""); folderName = folderName.Replace("\\" + folderName.FileName(), ""); zip.AddFile(file, folderName); } zip.Save(outputZipFilename); } } catch (Exception e1) { error.SetError(e1.Message, ""); } return(error); }
private static bool Save(List <string> files) { try { if (File.Exists(ZipfilePath)) { File.Delete(ZipfilePath); } Thread.Sleep(500); using (ZipFile zip = new ZipFile()) { foreach (string file in files) { zip.AddFile(file); } zip.Save(ZipfilePath); } return(true); } catch { return(false); } }
public static void Comprimir(string filePath, string zipName) { ZipFile zip; try { using (zip = new ZipFile()) { zip.AddFile(filePath, string.Empty); zip.Save(zipName); } } catch (Exception ex) { throw ex; } finally { zip = null; } }
// Takes an array of files to zip, returns an array of files which have been generated private void zipTheseFiles(string[] embedFiles, string outputLocation) { // ZIP it, MD5 it, and rename the file to MD5 + correct file extension ZipFile zip = new ZipFile(); string tempFile = outputLocation + @"\temp.zip"; // For each payload zip it foreach (string thisfile in embedFiles) { zip.AddFile(thisfile, ""); zip.Save(tempFile); copyFileUniqueFilename(tempFile, outputLocation); // MessageBox.Show("Zipfile '" + filename + "' created"); // TODO log zip.RemoveEntry(Path.GetFileName(thisfile)); } // Destroy zip, remove tempfile System.IO.File.Delete(tempFile); }
public static bool Zip_Files(List <string> listSelectedFile, string Password, string DestinationPath, string ZipName) { if (listSelectedFile != null) { using (ZipFile zip = new ZipFile()) { zip.Password = (Password); foreach (var sFile in listSelectedFile) { zip.AddFile(sFile); } zip.Save(DestinationPath + "\\" + ZipName + extension); return(true); } } return(false); }
public static void ZipFiles(string[] files, string destination) { using (var zip = new ZipFile()) { foreach (var file in files) { if (System.IO.File.Exists(file)) { zip.AddFile(file); } zip.Save(destination); } if (R.DebugMode && files.Length > 0) { var track = Diagnostic.TrackMessages(files); Diagnostic.Debug(typeof(File).Name, track, "Compacted {0} files to {1}", files.Length, destination); } } }
public void DownloadFilesChkBox() { using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; string[] s = Request.Form["chkselect"].Split(','); foreach (string value in s) { string filePath = value.ToString(); zip.AddFile(filePath, ""); } Response.Clear(); Response.BufferOutput = false; string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "attachment; filename=" + zipName); zip.Save(Response.OutputStream); Response.End(); } }
private void btnTestCompress_Click(object sender, EventArgs e) { using (var zip = new ZipFile(Encoding.Default)) { if (System.IO.File.Exists(txtFilePath.Text)) { zip.AddFile(txtFilePath.Text); } if (Directory.Exists(txtDirPath.Text)) { DirectoryInfo di = new DirectoryInfo(txtDirPath.Text); zip.AddDirectory(di.FullName, di.Name); } zip.Save(DEFAULT_ZIP_FILE_NAME); LogOperate("Compressed File:" + DEFAULT_ZIP_FILE_NAME); System.Diagnostics.Process.Start("explorer.exe", Application.StartupPath); } }
private void btnMakeFullArchive_Click(object sender, EventArgs e) { using (ZipFile zip = new ZipFile(Encoding.GetEncoding("shift_jis"))) { zip.CompressionLevel = CompressionLevel.BestCompression; //ファイルを追加 AddDllFilesToZip(zip); AddBinFilesToZip(zip, ""); CopyFile(publishDir + "\\" + dbUpdateFile, dbUpdateFile); CopyFile(publishDir + "\\" + dbFile, dstDbFile); RunDatabaseUpdater(dstDbFile, dbUpdateFile); zip.AddFile(dstDbFile); string target = Archiver.Properties.Settings.Default.archivePrefix + "v" + GetVersionStr(binDir + "\\" + Archiver.Properties.Settings.Default.mainBin) + ".zip"; zip.Save(target); } MessageBox.Show("正常終了"); }
public string exportar(List <string> files) { try { ZipFile zip = new ZipFile(); foreach (var f in files) { zip.AddFile(f); } string filename = "Exportacion" + DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".zip"; zip.Save(filename); return(filename); } catch (Exception ex) { throw ex; } }
public ActionResult Index(List <ArchivoModel> files) { using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AddDirectoryByName("Files"); foreach (ArchivoModel file in files) { if (file.IsSelected) { zip.AddFile(file.FilePath, "Files"); } } string zipName = String.Format("Comprimido_{0}.zip", DateTime.Now.ToString("yyyyMMdd-HHmm")); using (MemoryStream memoryStream = new MemoryStream()) { zip.Save(memoryStream); return(File(memoryStream.ToArray(), "application/zip", zipName)); } } }
/// <summary> /// Архивирование файла или папки. /// </summary> /// <param name="NewName">Путь, куда нужно сохранить архив.</param> public void arhiv(string NewName) { try { ZipFile _str = new ZipFile(NewName); foreach (string s in SDirectory.GetDirectories(dname)) { _str.AddDirectory(s, s); foreach (string f in SDirectory.GetFiles(s)) { _str.AddFile(f, s); } } _str.Save(NewName); } catch (Exception e) { LogForOperations("Архивирование папки", e.Message); throw e; } }
static void Test5() { using (var zf = new ZipFile()) { zf.AddFile("XCode.pdb"); zf.AddFile("NewLife.Core.pdb"); zf.Write("test.zip"); zf.Write("test.7z"); } //using (var zf = new ZipFile("Test.lzma.zip")) //{ // foreach (var item in zf.Entries.Values) // { // Console.WriteLine("{0} {1}", item.FileName, item.CompressionMethod); // } // zf.Extract("lzma"); //} }
public void Password_AddEntryWithPasswordToExistingZip() { string zipFileToCreate = "AddEntryWithPasswordToExistingZip.zip"; string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), }; string[] checksums = { TestUtilities.GetCheckSumString(filenames[0]), TestUtilities.GetCheckSumString(filenames[1]), }; int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) zip.AddFile(filenames[j], ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 2, "wrong number of entries."); string fileX = Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Unzip"), "unzip.exe"); string checksumX = TestUtilities.GetCheckSumString(fileX); string password = TestUtilities.GenerateRandomPassword() + "!"; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { zip.Password = password; zip.AddFile(fileX, ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 3, "wrong number of entries."); string unpackDir = "unpack"; string newpath, chk, baseName; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { baseName = Path.GetFileName(filenames[j]); zip[baseName].Extract(unpackDir, ExtractExistingFileAction.OverwriteSilently); newpath = Path.Combine(unpackDir, filenames[j]); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual<string>(checksums[j], chk, "Checksums do not match."); } baseName = Path.GetFileName(fileX); zip[baseName].ExtractWithPassword(unpackDir, ExtractExistingFileAction.OverwriteSilently, password); newpath = Path.Combine(unpackDir, fileX); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual<string>(checksumX, chk, "Checksums do not match."); } }
private void CreateSmallZip(string zipFileToCreate) { // the list of filenames to add to the zip string[] fileNames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), Path.Combine(SourceDir, "Tools", "WinFormsApp", "Icon2.res"), }; using (ZipFile zip = new ZipFile()) { for (int j = 0; j < fileNames.Length; j++) zip.AddFile(fileNames[j], ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), fileNames.Length, "Wrong number of entries."); }
public void SaveZipToFile(FileName toSave) { ZipFile zip = new ZipFile(toSave.FullName); foreach (ZipListItem item in list) { switch (item.Type) { case ZipListItemType.FILE: zip.AddFile(item.Item, item.PathInZip.Path); break; case ZipListItemType.FOLDER: zip.AddDirectory(item.Item, item.PathInZip.Path); break; default: break; } } zip.Save(); }
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(); } }
[ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile() { int i; string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile.zip"); string sourceDir = CurrentDir; for (i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Tools\\Unzip\\bin\\Debug\\Unzip.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; // create the zipfile, adding the files using (ZipFile zip = new ZipFile()) { for (i = 0; i < filenames.Length; i++) zip.AddFile(filenames[i], ""); zip.Save(zipFileToCreate); } // now corrupt the zip archive IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = new ZipFile(zipFileToCreate)) { foreach (var e in zip) { System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); e.Extract("extract"); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } }
public void Error_AddFile_SpecifyingDirectory() { string zipFileToCreate = "AddFile_SpecifyingDirectory.zip"; string badfilename = "ThisIsADirectory.txt"; Directory.CreateDirectory(badfilename); using (ZipFile zip = new ZipFile()) { zip.AddFile(badfilename); // should fail zip.Save(zipFileToCreate); } }
private void CreateSmallZip(string zipFileToCreate) { string sourceDir = CurrentDir; for (int i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); // the list of filenames to add to the zip string[] fileNames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; using (ZipFile zip = new ZipFile()) { for (int j = 0; j < fileNames.Length; j++) zip.AddFile(fileNames[j], ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), fileNames.Length, "Wrong number of entries."); }
private void btnExportar_Click(object sender, EventArgs e) { string pastaExportacao = Program.raizExportacao + "\\Exportados"; if (!Directory.Exists(pastaExportacao)) Directory.CreateDirectory(pastaExportacao); if (txtCnpj.Text.Length < 10 || txtRazaoSocial.Text.Length < 5 || txtNomeFantasia.Text.Length < 5 || txtUsuario.Text.Length < 2) { MessageBox.Show("Digite dados válidos"); return; } bool valido = Utils.ValidaCNPJ(txtCnpj.Text); if (!valido) { MessageBox.Show("O Cpnj não é válido"); return; } IDataReader dr; string arquivo; try { txtCnpj.Text = txtCnpj.Text.ToUpper(); txtNomeFantasia.Text = txtNomeFantasia.Text.ToUpper(); txtRazaoSocial.Text = txtRazaoSocial.Text.ToUpper(); txtUsuario.Text = txtUsuario.Text.ToUpper(); arquivo = "c:\\DadosExportados "+ txtNomeFantasia.Text +".dbf"; if (File.Exists(arquivo)) File.Delete(arquivo); IObjectContainer dbXXX = Db4oFactory.OpenFile(arquivo); #region Marca e Seção Cad_Marca marca = new Cad_Marca(); marca.id = AppFacade.get.reaproveitamento.getIncremento(dbXXX, typeof(Cad_Marca), 0); marca.idClienteFuncionarioLogado = 1; marca.marca = "GERAL"; dbXXX.Store(marca); Cad_Secao secao = new Cad_Secao(); secao.id = AppFacade.get.reaproveitamento.getIncremento(dbXXX, typeof(Cad_Secao), 0); secao.idClienteFuncionarioLogado = 1; secao.secao = "GERAL"; secao.grupo = "GERAL"; dbXXX.Store(secao); #endregion #region Pessoas //exportador normal /* Escreve("Escrevendo Pessoas"); { Empresa emp = ExportaEmpresas(dbXXX); dbXXX.Store(emp); } * */ { //propriedades dr = readOdbc(Program.raizExportacao + "\\COMUM", "PROPRIED.DBF"); DataSet dtstProp = new DataSet(); dtstProp.Load(dr, LoadOption.OverwriteChanges, "tbl_propriedades"); dtProp = dtstProp.Tables[0]; dicPropri = new Dictionary<int, List<DataRow>>(); foreach (DataRow drow in dtProp.Rows) { if (drow["CLIE_PRO"] is Double) { int codigoCli = Convert.ToInt32(drow["CLIE_PRO"]); if (!dicPropri.ContainsKey(codigoCli)) dicPropri[codigoCli] = new List<DataRow>(); dicPropri[codigoCli].Add(drow); } } } //exportador normal /* #region Clientes Escreve("Escrevendo Clientes"); dr = readOdbc(Program.raizExportacao + "\\COMUM", "CLIENTES.DBF"); ExportaClientes(dr, dbXXX); #endregion #region Fornecedores Escreve("Escrevendo Fornecedores"); dr = readOdbc(Program.raizExportacao + "\\COMUM", "FORNECED.DBF"); ExportaFornecedores(dr, dbXXX); #endregion * */ //exportador obra densa #region Fornecedores Escreve("Escrevendo Fornecedores"); dr = readOdbc(Program.raizExportacao + "\\COMUM", "FORNECED.DBF"); ExportaFornecedores(dr, dbXXX); #endregion #region Clientes Escreve("Escrevendo Clientes"); dr = readOdbc(Program.raizExportacao + "\\COMUM", "CLIENTES.DBF"); ExportaClientes(dr, dbXXX); #endregion Escreve("Escrevendo Pessoas"); { Empresa emp = ExportaEmpresas(dbXXX); dbXXX.Store(emp); } /* //fiz isso pra inverter 1(UM) id do SDE para o cliente consumidor funcionar corretamente IQuery query = dbXXX.Query(); query.Constrain(typeof(Cliente)); IObjectSet rs_listaClientes = query.Execute(); int indice = rs_listaClientes.Count - 2; Cliente clienteConsumidor = rs_listaClientes[indice] as Cliente; clienteConsumidor.id = 1; dbXXX.Store(clienteConsumidor); Cliente fornecedorBastardo = rs_listaClientes[0] as Cliente; clienteConsumidor.id = indice; dbXXX.Store(fornecedorBastardo); * */ #endregion #region Itens Escreve("Escrevendo Itens"); dr = readOdbc(Program.raizExportacao + "\\DADOS1", "PRODUTOS.DBF"); ExportaItens(dr, dbXXX); #endregion string cpf_cnpj_restringido = (novosCli[1] as Cliente).cpf_cnpj; int index = 0; List<Cliente> cEndList = new List<Cliente>(); //retirei para testes na exportação obra densa /* foreach (Cliente cli in novosCli) { if (cli.cpf_cnpj == cpf_cnpj_restringido && cli.id != 1) index = novosCli.IndexOf(cli); if (cli.__enderecos != null) { if (cli.id != 1 && cli.id != 2) if (cli.__enderecos.Count == 0) { cEndList.Add(cli); reprovadosCli.Add(cli); } } else if (cli.id != 1 && cli.id != 2) { cEndList.Add(cli); reprovadosCli.Add(cli); } } * */ novosCli.RemoveAt(index); foreach (Cliente cEnd in cEndList) novosCli.Remove(cEnd); foreach (Object o in novosCli) dbXXX.Store(o); foreach (Object o in novosItem) dbXXX.Store(o); Escreve("exportados:"); Escreve("clientes: " + novosCli.Count.ToString()); Escreve("produtos:" + novosItem.Count.ToString()); Escreve("falhos:"); Escreve("clientes: " + reprovadosCli.Count.ToString()); Escreve("produtos:" + reprovadosItem.Count.ToString()); dbXXX.Commit(); dbXXX.Dispose(); ZipFile zip = new ZipFile(); zip.AddFile(arquivo); zip.Save(pastaExportacao + "\\dados_exportacao.zip"); File.Delete(arquivo); arquivo = pastaExportacao + "\\1.Clientes.xml"; using (TextWriter tw = new StreamWriter(arquivo + "_reprovados.xml")) { new XmlSerializer(novosCli.GetType()).Serialize(tw, reprovadosCli); } arquivo = pastaExportacao + "\\2.Produtos.xml"; using (TextWriter tw = new StreamWriter(arquivo + "_reprovados.xml")) { new XmlSerializer(reprovadosItem.GetType()).Serialize(tw, reprovadosItem); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); this.Close(); } }
/// <summary> /// Save the EPUB using Ionic zip library /// </summary> /// <param name="EpubFileName"></param> private void SaveEpubFile(String EpubFileName) { if (File.Exists(EpubFileName)) File.Delete(EpubFileName); using (ZipFile zip = new ZipFile(EpubFileName)) { // MUST save the 'mimetype' file as the first file and non-compressed zip.ForceNoCompression = true; zip.AddFile(Path.Combine(mainDir, "mimetype"), ""); // Can compress all other files zip.ForceNoCompression = false; zip.AddDirectory(metaDir, "META-INF"); zip.AddDirectory(opsDir, "OPS"); zip.Save(); Directory.Delete(mainDir, true); if (ddlType.Text == "Html") if (workingFileName.ToLower() != tbxFileName.Text.ToLower()) File.Delete(workingFileName); } }
private void UploadFiles(StringCollection files) { if (files.Count > 1 && (bool)Properties.Settings.Default["combinezip"]) { string tempfile = Path.GetTempPath() + "\\qpaste.zip"; File.Delete(tempfile); using (ZipFile zip = new ZipFile(tempfile)) { foreach (string file in files) { FileAttributes attr = File.GetAttributes(file); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { Debug.WriteLine(Path.GetFileName(file)); zip.AddDirectory(file, Path.GetFileName(file)); } else { zip.AddFile(file, ""); } } zip.Save(); } Token token = UploadHelper.getToken(tempfile); ClipboardHelper.PasteWithName("Multiple files", token.link); UploadHelper.Upload(tempfile, token); File.Delete(tempfile); } else { foreach (string file in files) { Token token = null; FileAttributes attr = File.GetAttributes(file); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { token = UploadHelper.getToken(file); ClipboardHelper.PasteWithName(Path.GetFileName(file), token.link); string tempfile = Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(file) + ".zip"; File.Delete(tempfile); using (ZipFile zip = new ZipFile(tempfile)) { zip.AddDirectory(file, ""); zip.Save(); } UploadHelper.Upload(tempfile, token); File.Delete(tempfile); } else { token = UploadHelper.getToken(file); ClipboardHelper.PasteWithName(Path.GetFileName(file), token.link); UploadHelper.Upload(file, token); } } } }
public static void GeneraOXT(Regles regles, string dirFitxer, string nomFitxer, CanviaString canvis) { // genera .oxt String path = dirFitxer + nomFitxer + ".oxt"; File.Delete(path); using (ZipFile zip = new ZipFile(path)) { zip.AddFile(dirFitxer + nomFitxer + ".dic", "dictionaries"); zip.AddFile(dirFitxer + nomFitxer + ".aff", "dictionaries"); zip.AddFile(dirFitxer + @"..\..\OXT\" + "LICENSES-en.txt",""); zip.AddFile(dirFitxer + @"..\..\OXT\" + "LLICENCIES-ca.txt", ""); zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + nomFitxer + "\dictionaries.xcu", canvis, "\r\n", Encoding.UTF8), "dictionaries.xcu", ""); zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + nomFitxer + "\description.xml", canvis, "\r\n", Encoding.UTF8), "description.xml", ""); //zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_en.txt", canvia), "release-notes_en.txt", ""); //zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_ca.txt", canvia), "release-notes_ca.txt", ""); zip.AddFile(dirFitxer + @"..\..\OXT\META-INF\" + "manifest.xml", "META-INF/"); zip.AddFile(dirFitxer + @"..\..\OXT\" + "SC-logo.png",""); zip.Save(); } // genera update.xml, release-notes_en.txt i release-notes_ca.txt path = dirFitxer + nomFitxer + ".update.xml"; using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) { sw.Write(AdaptaFitxer(dirFitxer + @"..\..\OXT\update.xml", canvis, "\r\n", Encoding.UTF8)); } string[] llengues = { "ca", "en" }; foreach (string llengua in llengues) { path = dirFitxer + "release-notes_" + llengua + ".html"; using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) { sw.Write(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_" + llengua + ".html", canvis, "\r\n", Encoding.UTF8)); } } }
protected void btnDownloadQuickStatsGadget_Click(object sender, EventArgs e) { string gadgetFile = Server.MapPath("~/Temp/" + Config.Misc.GadgetsPrefix + " " + ((PageBase)Page).CurrentUserSession.Username + " Quick Stats.gadget"); if (File.Exists(gadgetFile)) File.Delete(gadgetFile); using (ZipFile zip = new ZipFile(gadgetFile)) { zip.BaseDir = Config.Directories.Home + @"\Gadgets\QuickStats\gadget\"; string[] filenames = Directory.GetFiles(Config.Directories.Home + @"\Gadgets\QuickStats\gadget"); foreach (String filename in filenames) { ZipEntry.FileParserDelegate parser = null; if (filename.Contains("gadget.htm")) parser = new ZipEntry.FileParserDelegate(QuickStatsGadgetParser); zip.AddFile(filename, false, parser); } zip.Save(); } Response.Clear(); Response.AppendHeader("content-disposition", String.Format("attachment; filename=\"{0}.gadget\"", string.Format("{0} Quick Stats".Translate(), Config.Misc.GadgetsPrefix))); Response.TransmitFile(gadgetFile); Response.End(); }
[ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile_Passwords() { string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile_Passwords.zip"); string sourceDir = CurrentDir; for (int i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; // passwords to use for those entries string[] passwords = { "12345678", "0987654321", }; // create the zipfile, adding the files int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j % passwords.Length]; zip.AddFile(filenames[j], ""); } zip.Save(zipFileToCreate); } IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); Assert.IsTrue(e.UsesEncryption, "The entry does not use encryption"); e.ExtractWithPassword("unpack", passwords[j % passwords.Length]); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } }
public void Password_Extract_WrongPassword() { string ZipFileToCreate = Path.Combine(TopLevelDir, "MultipleEntriesDifferentPasswords.zip"); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); string SourceDir = CurrentDir; for (int i = 0; i < 3; i++) SourceDir = Path.GetDirectoryName(SourceDir); Directory.SetCurrentDirectory(TopLevelDir); string[] filenames = { Path.Combine(SourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(SourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), }; string[] passwords = { "12345678", "0987654321", }; int j = 0; using (ZipFile zip = new ZipFile(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j]; zip.AddFile(filenames[j], ""); } zip.Save(); } // now try to extract using (ZipFile zip = new ZipFile(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, "WrongPassword"); } }
public void Error_LockedFile_wi13903() { TestContext.WriteLine("==Error_LockedFile_wi13903()"); string fname = Path.GetRandomFileName(); TestContext.WriteLine("create file {0}", fname); TestUtilities.CreateAndFillFileText(fname, _rnd.Next(10000) + 5000); string zipFileToCreate = "wi13903.zip"; var zipErrorHandler = new EventHandler<ZipErrorEventArgs>( (sender, e) => { TestContext.WriteLine("Error reading entry {0}", e.CurrentEntry); TestContext.WriteLine(" (this was expected)"); e.CurrentEntry.ZipErrorAction = ZipErrorAction.Skip; }); // lock the file TestContext.WriteLine("lock file {0}", fname); using (var s = System.IO.File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.None)) { using (var rawOut = File.Create(zipFileToCreate)) { using (var nonSeekableOut = new Ionic.Zip.Tests.NonSeekableOutputStream(rawOut)) { TestContext.WriteLine("create zip file {0}", zipFileToCreate); using (var zip = new ZipFile()) { zip.ZipError += zipErrorHandler; zip.AddFile(fname); // should trigger a read error, // which should be skipped. Result will be // a zero-entry zip file. zip.Save(nonSeekableOut); } } } } TestContext.WriteLine("all done, A-OK"); }
///////////////////////////////////////////////////// // // // DoCollect() // // // ///////////////////////////////////////////////////// //Description: Collects all files identified in the scan // as malicious and stuffs them into a // password-protected, encrypted ZIP file. // // NOTE: depends on DoSignatureScan() // // //Returns: true if successful ////////////////////////////////////////////////////// private unsafe bool DoCollect() { AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(" COLLECT "); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("COLLECT: Collecting evidence files..."); //collect the following files to wrap up in archive file: // 1. all identified malware files // 2. infection log (Infection_Log.txt) which we create // 3. usb device list file (USB_Devices.txt) which we create // 4. .net installation log (if exists) // //--------------------------------- // BUILD ZIP NAME //--------------------------------- ZipFileName = Collect.BuildZipName(TotalFindingsCount); ZipFile zip = new ZipFile(ZipFileName); if (AgentSettings.ContainsKey("Reporting_Archive_Password")) { IntPtr pptr = IntPtr.Zero; //do this secure string thing if password specified char[] str = AgentSettings["Reporting_Archive_Password"].ToCharArray(); fixed (char* pChars = str) { ZipPassword = new SecureString(pChars, str.Length); } //decrypt our password in memory pptr = Marshal.SecureStringToBSTR(ZipPassword); zip.Password = Marshal.PtrToStringBSTR(pptr); //zero the password memory Marshal.ZeroFreeBSTR(pptr); } zip.TempFileFolder = "."; ArrayList CollectList = new ArrayList(); int count = 0; AgentScanLog.AppendLine("COLLECT: Searching file signature matches for files..."); //loop through file signatures foreach (CwXML.FileSignatureMatch fileMatch in AgentSignatureMatches.FileSignatureMatches) if (Collect.AddToZip(zip, fileMatch.FullPath)) count++; AgentScanLog.AppendLine("COLLECT: Added " + count + " files."); count = 0; AgentScanLog.AppendLine("COLLECT: Searching registry signature matches for files..."); //loop through registry signatures foreach (CwXML.RegistrySignatureMatch registryMatch in AgentSignatureMatches.RegistrySignatureMatches) if (registryMatch.IsFileOnDisk) if (Collect.AddToZip(zip, registryMatch.RegistryValueData)) count++; AgentScanLog.AppendLine("COLLECT: Added " + count + " files."); AgentScanLog.AppendLine("COLLECT: Generating infection summary report..."); //--------------------------------- // ADD INFECTION LOG //--------------------------------- //2. infection log (Infection_Log.txt) which we create StreamWriter infectionlog = new StreamWriter("InfectionLog.txt"); StringBuilder InfectionSummaryReport = new StringBuilder(); //print infection summary for each signature type RegistryHelper RegHelper = new RegistryHelper(); FileHelper FileHelper = new FileHelper(); MemoryHelper MemHelper = new MemoryHelper(); RegHelper.PrintRegistryFindings(AgentSignatureMatches.RegistrySignatureMatches, ref InfectionSummaryReport); FileHelper.PrintFileFindings(AgentSignatureMatches.FileSignatureMatches, ref InfectionSummaryReport); MemHelper.PrintMemoryFindings(AgentSignatureMatches.MemorySignatureMatches, ref InfectionSummaryReport); infectionlog.WriteLine(InfectionSummaryReport.ToString()); infectionlog.Close(); zip.AddFile("InfectionLog.txt"); AgentScanLog.AppendLine("COLLECT: Enumerating USB Devices..."); //--------------------------------- // ADD USB DEVICES LOG //--------------------------------- //3. usb device list file (USB_Devices.txt) which we create StreamWriter usblogfile = new StreamWriter("USB_Devices.txt"); StringBuilder UsbDevicesReport = new StringBuilder(); Collect.EnumerateUSBDevices(ref UsbDevicesReport); usblogfile.WriteLine(UsbDevicesReport.ToString()); usblogfile.Close(); zip.AddFile("USB_Devices.txt"); //--------------------------------- // ADD .NET LOG //--------------------------------- //4. .net installation log (if exists) try { FileInfo dotnetfxLogfile = new FileInfo("dotnetfx_install_log.txt"); if (dotnetfxLogfile.Exists) zip.AddFile("dotnetfx_install_log.txt"); } catch { } //no biggie.. AgentScanLog.AppendLine("COLLECT: All evidence collected."); AgentScanLog.AppendLine("COLLECT: Saving zip to disk..."); zip.Save(); zip.Dispose(); //at this point zip is closed and written to disk return true; }
public void Password_MultipleEntriesDifferentPasswords() { string ZipFileToCreate = Path.Combine(TopLevelDir, "Password_MultipleEntriesDifferentPasswords.zip"); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); string SourceDir = CurrentDir; for (int i = 0; i < 3; i++) SourceDir = Path.GetDirectoryName(SourceDir); Directory.SetCurrentDirectory(TopLevelDir); string[] filenames = { Path.Combine(SourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(SourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), }; string[] checksums = { TestUtilities.GetCheckSumString(filenames[0]), TestUtilities.GetCheckSumString(filenames[1]), }; string[] passwords = { "12345678", "0987654321", }; int j = 0; using (ZipFile zip = new ZipFile(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j]; zip.AddFile(filenames[j], ""); } zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(ZipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); using (ZipFile zip = new ZipFile(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, passwords[j]); string newpath = Path.Combine("unpack", filenames[j]); string chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual<string>(checksums[j], chk, "File checksums do not match."); } } }
public static void ZipFiles(IEnumerable<string> fileNames, string targetFile) { ZipFile zipedFile = new ZipFile(); foreach (string file in fileNames) { zipedFile.AddFile(file, String.Empty); } zipedFile.Save(targetFile); }
public void Password_AddEntryWithPasswordToExistingZip() { string zipFileToCreate = "AddEntryWithPasswordToExistingZip.zip"; string dnzDir = CurrentDir; for (int i = 0; i < 3; i++) dnzDir = Path.GetDirectoryName(dnzDir); string[] filenames = { Path.Combine(dnzDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(dnzDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), }; string[] checksums = { TestUtilities.GetCheckSumString(filenames[0]), TestUtilities.GetCheckSumString(filenames[1]), }; int j = 0; using (ZipFile zip = new ZipFile(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) zip.AddFile(filenames[j], ""); zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 2, "wrong number of entries."); string fileX = Path.Combine(dnzDir, "Tools\\Unzip\\bin\\debug\\unzip.exe"); string checksumX = TestUtilities.GetCheckSumString(fileX); string password = TestUtilities.GenerateRandomPassword() + "!"; using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.Password = password; zip.AddFile(fileX, ""); zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 3, "wrong number of entries."); string unpackDir = "unpack"; string newpath, chk, baseName; using (ZipFile zip = new ZipFile(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { baseName = Path.GetFileName(filenames[j]); zip[baseName].Extract(unpackDir, ExtractExistingFileAction.OverwriteSilently); newpath = Path.Combine(unpackDir, filenames[j]); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual<string>(checksums[j], chk, "Checksums do not match."); } baseName = Path.GetFileName(fileX); zip[baseName].ExtractWithPassword(unpackDir, ExtractExistingFileAction.OverwriteSilently, password); newpath = Path.Combine(unpackDir, fileX); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual<string>(checksumX, chk, "Checksums do not match."); } }
protected void btnGenerateAdminStatsGadget_Click(object sender, EventArgs e) { if (!HasWriteAccess) return; string gadgetFile = Path.GetTempPath() + Config.Misc.GadgetsPrefix + " Admin Stats.gadget"; if (File.Exists(gadgetFile)) File.Delete(gadgetFile); using (ZipFile zip = new ZipFile(gadgetFile)) { zip.BaseDir = Config.Directories.Home + @"\Gadgets\AdminStats\gadget\"; string[] filenames = Directory.GetFiles(Config.Directories.Home + @"\Gadgets\AdminStats\gadget"); foreach (String filename in filenames) { ZipEntry.FileParserDelegate parser = null; if (filename.Contains("gadget.htm")) parser = new ZipEntry.FileParserDelegate(FileParser); zip.AddFile(filename, false, parser); } zip.Save(); } Response.Clear(); Response.AppendHeader("content-disposition", String.Format("attachment; filename=\"{0}.gadget\"", Config.Misc.GadgetsPrefix + " Admin Stats")); Response.TransmitFile(gadgetFile); Response.End(); }