private void button1_Click(object sender, EventArgs e) { if (Game.ship.id == null) { throw new InvalidDataException("**** Error! ****\n You have not set a ship ID! Please set one before exporting!!"); } string outputFolder = Path.Combine(Application.StartupPath, Game.ship.id); Directory.CreateDirectory(outputFolder); Directory.CreateDirectory(Path.Combine(outputFolder, "img")); Directory.CreateDirectory(Path.Combine(outputFolder, "img\\ship")); Directory.CreateDirectory(Path.Combine(outputFolder, "data")); Game.game.ExportLayoutTxt(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".txt")); Game.game.ExportLayoutXML(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".xml")); Game.game.ExportBlueprintXML(Path.Combine(outputFolder, "data\\" + "blueprints.xml.append"), append: true); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Path.Combine(outputFolder, Game.ship.name + string.Format("-{0:yyyy-MM-dd_hh-mm-ss}", DateTime.Now) + ".ftl")); if (Directory.Exists(Path.Combine(outputFolder, "img"))) zip.AddDirectory(Path.Combine(outputFolder, "img"), "\\img"); if (Directory.Exists(Path.Combine(outputFolder, "data"))) zip.AddDirectory(Path.Combine(outputFolder, "data"), "\\data"); if (Directory.Exists(Path.Combine(outputFolder, "audio"))) zip.AddDirectory(Path.Combine(outputFolder, "audio"), "\\audio"); zip.Save(); System.Diagnostics.Process.Start(outputFolder); }
public void ZipDirectory(string zipFilePath, string directoryPathToCompress, string directoryPathInArchive) { Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipFilePath); zf.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zf.AddDirectory(directoryPathToCompress, directoryPathInArchive); zf.AddProgress += delegate(object sender, Ionic.Zip.AddProgressEventArgs e) { Console.WriteLine("\tAdding " + e.CurrentEntry.FileName); }; zf.Save(); }
public static bool CreateZipArchiv(string[] files, string zipArchiv) { var zipFile = new Ionic.Zip.ZipFile(zipArchiv); foreach (var file in files) { if (File.GetAttributes(file).HasFlag(FileAttributes.Directory)) { zipFile.AddDirectory(file,new DirectoryInfo(file).Name); } else { zipFile.AddFile(file,String.Empty); } zipFile.Save(); } return true; }
public static List <string> ZipAndCopyEpubs(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var destination = Path.Combine("Samples", Path.GetFileName(path)); if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } var samples = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly).ToList(); var archives = new List <string>(); foreach (var source in samples) { var archiveName = Path.GetFileName(source) + ".zip"; var archivePath = Path.Combine(destination, archiveName); if (!File.Exists(archivePath)) { using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(source, archivePath); zip.Save(); } } archives.Add(archivePath); } return(archives); }
public void CompressFilesWithZip(string directory, List <string> sourceFiles, string zipFile, string passWord) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile, Encoding.UTF8)) { zip.Password = passWord == string.Empty ? string.Empty : passWord; try { foreach (string detail in sourceFiles) { zip.AddFile(detail); zip.AddDirectory(directory); } } catch { } finally { zip.Save(); zip.Dispose(); } } //sample //using (ZipFile zip = new ZipFile("Backup.zip")) //{ // zip.AddFile("ReadMe.txt"); // no password for this entry // zip.Password = "******"; // ZipEntry e = zip.AddFile("7440-N49th.png"); // e.Comment = "Map of the company headquarters."; // zip.Password = "******"; // zip.AddFile("2Q2008_Operations_Report.pdf"); // zip.Save(); //} }
private void DoZip() { try { this.Verify(); if (FolderOption == ZipEnum.Single) { folderArray = new string[] { folderPath }; } using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { if (!string.IsNullOrEmpty(pwd)) { zip.Password = pwd; } foreach (string item in folderArray) { DirectoryInfo directoryInfo = new DirectoryInfo(item); zip.AddDirectory(item, directoryInfo.Name); } zip.Save(filePath); } } catch (Exception ex) { throw ex; } }
private void btnZipFolder_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtFolder.Text)) { MessageBox.Show("Please select your folder", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); txtFolder.Focus(); return; } string path = txtFolder.Text; Thread thread = new Thread(t => { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(path); System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path); zip.SaveProgress += Zip_SaveProgress; zip.Save(string.Format("{0}{1}.zip", directoryInfo.Parent.FullName, directoryInfo.Name)); } }) { IsBackground = true }; thread.Start(); }
public static void ZipAndroidProject(string dir) { using (var zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("gbk"))) { zip.AddFiles(Directory.GetFiles(dir).Where(i => !i.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)).ToArray(), ""); zip.AddFiles(Directory.GetFiles(Path.Combine(dir, "app")), "app"); zip.AddDirectory(Path.Combine(Path.Combine(dir, "app"), "src"), "app/src"); zip.AddDirectory(Path.Combine(dir, "gradle"), "gradle"); var targetFileName = Path.Combine(dir, Path.GetFileName(dir) + ".zip"); var count = 0; while (File.Exists(targetFileName)) { targetFileName = Path.Combine(dir, string.Format("{0} {1:000}.zip", Path.GetFileName(dir), ++count)); } zip.Save(targetFileName); } }
// http://stackoverflow.com/questions/1578823/creating-a-zip-extractor public static void CreateSelfExtra() { string DirectoryToZip = ""; string ZipFileToCreate = ""; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.Comment = "This will be embedded into a self-extracting console-based exe"; //zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(DirectoryToZip); // recurses subdirectories //zip.Password = "******"; //zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256; //zip.Save(ZipFileToCreate); Ionic.Zip.SelfExtractorSaveOptions options = new Ionic.Zip.SelfExtractorSaveOptions(); options.Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication; //options.DefaultExtractDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), System.IO.Directory.GetParent(ZipFileToCreate).Name); options.DefaultExtractDirectory = "%TEMP%"; options.ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently; // http://dotnetzip.codeplex.com/workitem/10682 //options.IconFile = System.IO.Path.Combine(Application.StartupPath, "box_software.ico"); //options.PostExtractCommandLine = "putty.exe"; //options.Quiet = true; //options.RemoveUnpackedFilesAfterExecute = true; zip.SaveSelfExtractor(System.IO.Path.ChangeExtension(ZipFileToCreate, ".exe"), options); } // End Using zip } // End Sub CreateSelfExtra
private void Button1_Click(object sender, EventArgs e) { string path = "c:\\testC\\zipTest"; try { Thread th = new Thread(t => { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(path); //DirectoryInfo di = new DirectoryInfo(path); zip.Save("c:\\testC\\abc.zip"); } }) { IsBackground = true }; th.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
/// <summary> /// Архивация логов. /// ВНИМАНИЕ!!! /// При архивации используется пароль, равный User ID. /// </summary> public void ArchiveLogs() { try { if (Properties.Resources.Default_Debug_Archive == "1") { if (File.Exists("Ionic.Zip.dll")) { if (Directory.Exists(MainWindow.SettingsDir + "temp")) { if (!Directory.Exists(MainWindow.SettingsDir + "debug")) { Directory.CreateDirectory(MainWindow.SettingsDir + "debug"); } using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { string uid = new Classes.Variables().GetUserID(); string version = Application.Current.GetType().Assembly.GetName().Version.ToString(); zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; zip.Password = uid; zip.AddDirectory(MainWindow.SettingsDir + "temp"); zip.Save(MainWindow.SettingsDir + @"debug\" + String.Format("{0}_{1}_{2}.zip", uid, version, DateTime.Now.ToString("yyyy-MM-dd h-m-s.ffffff"))); } Directory.Delete(MainWindow.SettingsDir + "temp", true); } } } } catch (Exception ex) { Save("Debugging.Class", "ArchiveLogs()", ex.Message, ex.StackTrace); } }
/// <summary> /// Worker Completed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { //create a zip file using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(_tempFolder); zip.Save(_zipFileName); } //delete temp dir DeleteDirectory(_tempFolder); string c; if (jira.IssuesBCFCollection.Count() == 1) { c = " Issue"; } else { c = " Issues"; } MessageBox.Show(jira.IssuesBCFCollection.Count().ToString() + c + " exported successfully!"); progress.Value = 0; progress.Visibility = System.Windows.Visibility.Hidden; mainwin.IsEnabled = true; } // END TRY catch (System.Exception ex1) { MessageBox.Show("exception: " + ex1); } }
public static void CreateZip() { using (var zip = new Ionic.Zip.ZipFile()) { using (FileStream fs = File.Create(SavingPath)) { zip.AddDirectory(OutputPath); zip.Save(fs); } } try { var dir = new DirectoryInfo(OutputPath); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); } catch (IOException ex) { FileParser.LogException(ex); } /*using (var zip = new Ionic.Zip.ZipFile()) * { * zip.AddDirectory(Environment.GetFolderPath( * System.Environment.SpecialFolder.DesktopDirectory) + "\\code"); * FileStream x = File.Create("D:\\Visual Studio\\CommandGenerator\\MyFile.zip"); * zip.Save(x); * x.Close(); * zip.Dispose(); * } */ }
private void ExportMethodNode(MethodTreeNode rootNode) { if (rootNode == null) { CommonMethod.ErrorMsgBox("没有选择需要输出的模型节点"); return; } Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = filter; if (dlg.ShowDialog() == true) { //在temp目录中创建rfdi目录 string rfdiDir = Path.Combine(Path.GetTempPath(), "rfdi_nodeExport"); if (!Directory.Exists(rfdiDir)) { Directory.CreateDirectory(rfdiDir); } CreateZipFileTree(rootNode, rfdiDir); if (File.Exists(dlg.FileName)) //如果压缩文件存在,删除该文件 { File.Delete(dlg.FileName); } using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(dlg.FileName, Encoding.GetEncoding(SettingData.UTF8))) { zip.AddDirectory(rfdiDir); zip.Save(); } Directory.Delete(rfdiDir, true); } }
private void ZipFolder_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(DirectoryPath.Text)) { WinForms.MessageBox.Show("Please select your folder.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); DirectoryPath.Focus(); return; } string path = DirectoryPath.Text; Thread thread = new Thread(t => { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(path); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); zip.SaveProgress += Zip_SaveProgress; zip.Save(string.Format($"{di.Parent.FullName}{di.Name}.zip")); } }) { IsBackground = true }; thread.Start(); }
public static void Zip(string path, string file) { using (var loanZip = new Ionic.Zip.ZipFile()) { loanZip.AddDirectory(path); loanZip.Save(file); } }
private void ZipDirectories() { var dirs = Directory.GetDirectories(textBoxFolder.Text); if (dirs == null || dirs.Length == 0) { MessageBox.Show("No directories found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int index = 1; new Thread(() => { foreach (var dir in dirs) { if (stop) { stop = false; Thread.CurrentThread.Abort(); } labelProcessing.Invoke((MethodInvoker) delegate { labelProcessing.Text = GetFileName(dir); labelProcessing.Refresh(); }); var zippedName = textBoxFolder.Text + "\\" + GetFileName(dir) + ".zip"; Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); zip.ParallelDeflateThreshold = -1; zip.AddDirectory(dir); if (File.Exists(zippedName)) { File.Delete(zippedName); } zip.Save(zippedName); labelCount.Invoke((MethodInvoker) delegate { labelCount.Text = index.ToString(); labelCount.Refresh(); }); index++; } labelProcessing.Invoke((MethodInvoker) delegate { labelProcessing.Text = "Done!"; labelProcessing.Refresh(); }); }).Start(); }
public void ZipGitFileAsync(string pathToFile, string projectId) { //ZipFile.CreateFromDirectory(pathToFile, pathToFile+".zip"); using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(pathToFile + "\\ProjectFolder\\.git", ".git"); zip.Save(pathToFile + $"\\ProjectFolder\\g{projectId}.zip"); } }
/// <summary> /// 压缩文件夹,文件架下面包含文件夹 /// </summary> /// <param name="filePath">源文件夹路径</param> /// <param name="savePath">保存为Zip包的目录</param> public static void ZipDirInfo(string filePath, string savePath) { using (var zip = new ZipFile()) { zip.StatusMessageTextWriter = Console.Out; zip.AddDirectory(filePath, @"\"); zip.Save(savePath); } }
public override void Build() { using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectoryByName("assets"); zip.AddDirectory(ResPath, "assets"); zip.Save(Path + "\\resources.zip"); } }
private void OverwriteEpub(string file, string tempFile) { File.Delete(file); using (var zip = new Ionic.Zip.ZipFile()) { var mime = zip.AddEntry("mimetype", "application/epub+zip", Encoding.ASCII); zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Never; mime.CompressionLevel = Ionic.Zlib.CompressionLevel.None; mime.CompressionMethod = Ionic.Zip.CompressionMethod.None; var metaDir = Path.Combine(tempFile, "META-INF"); var meta = zip.AddDirectory(metaDir, "META-INF"); meta.CompressionLevel = Ionic.Zlib.CompressionLevel.None; var contentDir = Path.Combine(tempFile, "OEBPS"); var content = zip.AddDirectory(contentDir, "OEBPS"); content.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zip.Save(file); } directory.Delete(tempFile, true); }
private bool CreateKMZ(string outputFilename, string templocation) { //create KML in temp location FileInfo fi = new FileInfo(outputFilename); string kmlfilename = Path.Combine(templocation, fi.Name.Replace("kmz", "kml")); CreateKML(kmlfilename); RaiseProgress("Creating KMZ..", 85); //Makezip using (Ionic.Zip.ZipFile kmz = new Ionic.Zip.ZipFile()) { kmz.CompressionLevel = Ionic.Zlib.CompressionLevel.None; kmz.AddFile(kmlfilename, ""); kmz.AddDirectory(thumbFolder, "Thumbnails"); kmz.AddDirectory(imageFolder, "Images"); kmz.Save(outputFilename); } return(true); }
public void ZipDirectory(string zipFilePath, string directoryPathToCompress, string directoryPathInArchive) { Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipFilePath); zf.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zf.AddDirectory(directoryPathToCompress, directoryPathInArchive); zf.AddProgress += delegate(object sender, Ionic.Zip.AddProgressEventArgs e) { Console.WriteLine("\tAdding " + e.CurrentEntry.FileName); }; zf.Save(); }
private void btn_TrasferimentoArchiviLocale_Click(object sender, RoutedEventArgs e) { //richiesta conferma Utilities u = new Utilities(); if (MessageBoxResult.No == u.ConfermaTrasferimentoArchivio()) { return; } //controllo percorso DirectoryInfo origine = new DirectoryInfo(App.AppDataFolder); string tmpzipfile = App.AppTempFolder + "zip" + Guid.NewGuid().ToString(); //Sposto archivio Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); zip.AddDirectory(origine.FullName); zip.Save(tmpzipfile); //Interfaccia radioButtonArchivioLocale.IsChecked = true; //setto variabili globali App.AppSetupTipoGestioneArchivio = App.TipoGestioneArchivio.Locale; //salvo nuova configurazione GestioneLicenza l = new GestioneLicenza(); l.SalvaInfoDataUltimoUtilizzo(); //Configuro path applicativi u.ConfiguraPercorsi(); //trasferisco archivio DirectoryInfo destinazione = new DirectoryInfo(App.AppDataFolder); zip.ExtractAll(destinazione.FullName, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); MasterFile.ForceRecreate(); //interfaccia //modifile all'interfaccia dell'ultimo momento radioButtonArchivioLocale.IsEnabled = false; radioButtonArchivioRemoto.IsEnabled = false; buttonSelezionaArchivioRemoto.IsEnabled = false; btn_TrasferimentoArchivi.IsEnabled = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Locale; btn_TrasferimentoArchiviLocale.IsEnabled = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Remoto; MessageBox.Show("Trasferimento archivio avvenuto con successo."); }
} // End Sub ZipWithDotNetZip public static void ZipAutoExtract() { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { // zip up a directory zip.AddDirectory("C:\\project1\\datafiles", "data"); zip.Comment = "This will be embedded into a self-extracting exe"; zip.AddEntry("Readme.txt", "This is content for a 'Readme' file that will appear in the zip."); zip.SaveSelfExtractor("archive.exe", Ionic.Zip.SelfExtractorFlavor.ConsoleApplication); } // End Using zip } // End Using ZipAutoExtract
void 压缩子目录ToolStripMenuItemClick(object sender, EventArgs e) { Helpers.OnClipboardFileSystem((path) => { var directories = Directory.GetDirectories(path); foreach (var element in directories) { using (var zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("gbk"))) { zip.AddDirectory(element); zip.Save(element + ".zip"); } } }); }
public static void ZipDirectories() { OnClipboardDirectory((dir) => { var directories = Directory.GetDirectories(dir); foreach (var element in directories) { using (var zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("gbk"))) { zip.AddDirectory(element); zip.Save(element + ".zip"); } } }); }
private void zip(String sourceDirectory, String destinationZipFile) { this._repo.taskDescription = "Zipping directory..."; this._repo.isIndetermerminate = true; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { if (this._repo.settings.encryptZipFile) { zip.Password = this._repo.settings.encryptionPassword; zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256; } zip.AddDirectory(sourceDirectory); zip.Save(destinationZipFile); } }
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { progressBar1.Value = 100; viewModel.IsRunning = false; if (Backup.OutputBackupFilePath != "") { var zip = new Ionic.Zip.ZipFile(); zip.UseUnicodeAsNecessary = true; //zip.AlternateEncoding = Encoding.UTF8; //zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed; zip.AddDirectory(Backup.TempFolderPath, null); zip.Save(Backup.OutputBackupFilePath); //zip.Dispose(); } }
public void Backup(ITaskContext context, string sourceDir, string destinationFileName) { if (Directory.Exists(sourceDir)) { context.LogInfo($"Zipping dir:{sourceDir} to: {destinationFileName}"); using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(sourceDir); zip.Save(destinationFileName); } } else { context.LogInfo($"SourceDir {sourceDir} not found. Skiping backup."); } }
private static byte[] makeAndReadZipData(string folderPath, out string zipPath, EncryptionArgv encArgv) { zipPath = folderPath + ".zip"; if (File.Exists(zipPath)) { zipPath = IOObject.RenameFolder(zipPath); } using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipPath, Encoding.UTF8)) { zip.CompressionLevel = encArgv.CompressLevel; zip.AddDirectory(folderPath, ""); zip.Comment = Path.GetFileName(folderPath); zip.Save(); } return(readAllFile(zipPath)); }
static void Main(string[] args) { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = "134.251.30.243", UserName = "******", Password = "******", }; string remoteDir = "test"; string path = "C:\\Users\\suyambu\\Desktop\\" + remoteDir; try { if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } } catch (IOException ioex) { //MessageBox.Show(ioex.Message); Console.WriteLine(ioex.Message); } using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Download files session.GetFiles("/" + remoteDir + "/*", @"C:\Users\suyambu\Desktop\" + remoteDir + "\\*").Check(); } string name = "test"; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory("C:\\Users\\suyambu\\Desktop\\" + name);//File to Zip // System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); // zip.SaveProgress += Zip_SaveProgress; // zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName,di.Name)); zip.Save("C:\\Users\\suyambu\\Desktop\\" + name + ".zip"); } }
private string CreateAdZip() { string zipfile = App.ZipPath; File.Delete(zipfile); using (var zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; //zip.SaveProgress += SaveProgress; zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(App.TmpDir, ""); zip.Save(zipfile); } return(zipfile); }
public static void DownloadFiles(List<string> archives, HttpContext httpContext) { if (archives.Count == 0) return; FileAttributes attr1 = System.IO.File.GetAttributes(archives[0]); if (archives.Count == 1 && ((attr1 & FileAttributes.Directory) != FileAttributes.Directory)) { string filename = Path.GetFileName(archives[0]); httpContext.Response.Buffer = true; httpContext.Response.Clear(); httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename); httpContext.Response.ContentType = "application/octet-stream"; httpContext.Response.WriteFile(archives[0]); } else { string zipName = String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); httpContext.Response.Buffer = true; httpContext.Response.Clear(); httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + zipName); httpContext.Response.ContentType = "application/zip"; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { foreach (string path in archives) { try { FileAttributes attr = System.IO.File.GetAttributes(path); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) zip.AddDirectory(path, Path.GetFileNameWithoutExtension(path)); else zip.AddFile(path, ""); } catch (Exception) { } } zip.Save(httpContext.Response.OutputStream); } } }
/// <summary> /// Do a simple zip of the given directory /// </summary> /// <param name="sourceDirPath"></param> /// <param name="targetZipPath"></param> /// <returns>True if succeeds</returns> public static bool zipChangeSetDir(string sourceDirPath, string targetZipPath) { try { if (string.IsNullOrEmpty(targetZipPath) || !Directory.Exists(sourceDirPath) || string.IsNullOrEmpty(sourceDirPath)) return false; createDirForFile(targetZipPath); using (Ionic.Zip.ZipFile zfile = new Ionic.Zip.ZipFile()) { zfile.AddDirectory(sourceDirPath); //zfile.AddDirectory(sourceDirPath + "\\new"); zfile.Save(targetZipPath); return true; } } catch (Exception) { return false; } }
public bool ZipDirectory(string SourceDirectory, string ZipFilePath, bool OverWrite = false) { try { // Make sure the specified Source Directory Exists. if (!System.IO.Directory.Exists(SourceDirectory)) { // Let the user know that the directory does not exist. if (ErrorMessage != null) { ErrorMessage("The specified source directory - " + SourceDirectory + " - does not exist. Aborting the MaintTools.ZipFileManager.ZipDirectory() Method!"); } // Return FALSE to the calling method to indicate that this method failed. return false; } // Make sure the specified output Directory Exists. if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(ZipFilePath))) { // Attempt to create the directory. System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(ZipFilePath)); } // Determine if the specified Output File already exists. string outputFilePath = ZipFilePath; if (System.IO.File.Exists(ZipFilePath)) { // If the user wants the old file overwritten, delete it. if (OverWrite) { System.IO.File.Delete(ZipFilePath); } else { // Try to find a file name to use. string outputBasePath = outputFilePath.Substring(0, (outputFilePath.Length - 4)); string extension = outputFilePath.Substring((outputFilePath.Length - 4)); int i = 0; outputFilePath = ""; while ((i < 100) && (outputFilePath.Length == 0)) { if (!System.IO.File.Exists(outputBasePath + "(" + i.ToString() + ")" + extension)) { outputFilePath = outputBasePath + "(" + i.ToString() + ")" + extension; } // Increment the counter. i++; } } } // Retrieve the Directory Name to be included in the Zip File. string directoryName = SourceDirectory; while (directoryName.IndexOf(@"\") != -1) { // Drop the Left Most character from the Directory Name. directoryName = directoryName.Substring(1); } // Attempt to zip the files in the directory. using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile()) { zipFile.AddDirectory(SourceDirectory, directoryName); zipFile.Comment = "This zip was created at " + System.DateTime.Now.ToString("G"); zipFile.Save(ZipFilePath); } } catch (System.Exception caught) { // Let the User know that this method failed. if (ErrorMessage != null) { ErrorMessage("The MaintTools.ZipFileManager.ZipDirectory() Method failed with error message: " + caught.Message); } // Return FALSE to the calling method to indicate that this process failed. return false; } // If the process made it to here, it was successful so return TRUE to the calling method. return true; }
/// <summary> /// Worker Completed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { //create a zip file using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(_tempFolder); zip.Save(_zipFileName); } //delete temp dir DeleteDirectory(_tempFolder); string c; if (jira.IssuesBCFCollection.Count() == 1) c = " Issue"; else c = " Issues"; MessageBox.Show(jira.IssuesBCFCollection.Count().ToString() + c + " exported successfully!"); progress.Value = 0; progress.Visibility = System.Visibility.Hidden; mainwin.IsEnabled = true; } // END TRY catch (System.Exception ex1) { MessageBox.Show("exception: " + ex1); } }
private void CreateZip(string destPath, string srcZipPath) { //ZipFileを作成する using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AlternateEncoding = System.Text.Encoding.GetEncoding("shift_jis"); zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.AsNecessary; //エラーが出てもスキップする。デフォルトはThrow。 zip.ZipErrorAction = Ionic.Zip.ZipErrorAction.Throw; zip.Comment = "donotopen"; zip.Password = "******"; zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256; //フォルダを追加する zip.AddDirectory(srcZipPath); zip.Save(destPath); } }
protected void btnExportarProyecto_Click(object sender, EventArgs e) { try { string nombre_proyecto = ""; if (txtnombreproyecto.Value.Length >= 15) nombre_proyecto = txtnombreproyecto.Value.Substring(0, 15); else nombre_proyecto = txtnombreproyecto.Value; var proyecto_info = (from p in new ESM.Model.ESMBDDataContext().Proyectos where p.Id == proyecto_id select p).Single(); string path = Server.MapPath("~/Files/Proyectos/"); if (Directory.Exists(path + nombre_proyecto)) { if (!Directory.Exists(path + nombre_proyecto + "/Actas")) Directory.CreateDirectory(path + nombre_proyecto + "/Actas"); if (!Directory.Exists(path + nombre_proyecto + "/Programacion")) Directory.CreateDirectory(path + nombre_proyecto + "/Programacion"); if (!Directory.Exists(path + nombre_proyecto + "/M.S.E")) Directory.CreateDirectory(path + nombre_proyecto + "/M.S.E"); string path_files = path + nombre_proyecto + @"\Programacion\MarcoLogico.xls"; string path_files_arbol_problemas = path + nombre_proyecto + @"\Programacion\ArbolProblemas.xls"; string path_files_arbol_objetivos = path + nombre_proyecto + @"\Programacion\ArbolObjetivos.xls"; string path_files_plan_accion = path + nombre_proyecto + @"\Programacion\PlanAccion.xls"; string html_marcologico = generateMarcoLogico(proyecto_id); string html_arbolproblemas = generateArbolProblemasOrg(); string html_arbolobjetivos = generateArbolObjetivosOrg(); string html_planaccion = generatePlanOperativo(proyecto_id); if (!File.Exists(path_files)) { StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8); objFile.Write(html_marcologico); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files); StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8); objFile.Write(html_marcologico); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_arbol_problemas)) { StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8); objFile.Write(html_arbolproblemas); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_arbol_problemas); StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8); objFile.Write(html_arbolproblemas); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_arbol_objetivos)) { StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8); objFile.Write(html_arbolobjetivos); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_arbol_objetivos); StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8); objFile.Write(html_arbolobjetivos); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_plan_accion)) { StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8); html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion; objFile.Write(html_planaccion); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_plan_accion); StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8); html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion; objFile.Write(html_planaccion); objFile.Flush(); objFile.Close(); } } else { Directory.CreateDirectory(path + "/" + nombre_proyecto); if (!Directory.Exists(path + nombre_proyecto + "/Actas")) Directory.CreateDirectory(path + nombre_proyecto + "/Actas"); if (!Directory.Exists(path + nombre_proyecto + "/Programacion")) Directory.CreateDirectory(path + nombre_proyecto + "/Programacion"); if (!Directory.Exists(path + nombre_proyecto + "/M.S.E")) Directory.CreateDirectory(path + nombre_proyecto + "/M.S.E"); string path_files = path + nombre_proyecto + @"\Programacion\MarcoLogico.xls"; string path_files_arbol_problemas = path + nombre_proyecto + @"\Programacion\ArbolProblemas.xls"; string path_files_arbol_objetivos = path + nombre_proyecto + @"\Programacion\ArbolObjetivos.xls"; string path_files_plan_accion = path + nombre_proyecto + @"\Programacion\PlanAccion.xls"; string html_marcologico = generateMarcoLogico(proyecto_id); string html_arbolproblemas = generateArbolProblemasOrg(); string html_arbolobjetivos = generateArbolObjetivosOrg(); string html_planaccion = generatePlanOperativo(proyecto_id); if (!File.Exists(path_files)) { StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8); objFile.Write(html_marcologico); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files); StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8); objFile.Write(html_marcologico); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_arbol_problemas)) { StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8); objFile.Write(html_arbolproblemas); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_arbol_problemas); StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8); objFile.Write(html_arbolproblemas); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_arbol_objetivos)) { StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8); objFile.Write(html_arbolobjetivos); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_arbol_objetivos); StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8); objFile.Write(html_arbolobjetivos); objFile.Flush(); objFile.Close(); } if (!File.Exists(path_files_plan_accion)) { StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8); html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion; objFile.Write(html_planaccion); objFile.Flush(); objFile.Close(); } else { File.Delete(path_files_plan_accion); StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8); html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion; objFile.Write(html_planaccion); objFile.Flush(); objFile.Close(); } } if (!File.Exists(path + nombre_proyecto + ".zip")) { using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(path + "/" + nombre_proyecto); zip.Save(path + nombre_proyecto + ".zip"); } } else { File.Delete(path + nombre_proyecto + ".zip"); using (var zip = new Ionic.Zip.ZipFile()) { zip.AddDirectory(path + "/" + nombre_proyecto); zip.Save(path + nombre_proyecto + ".zip"); } } Response.Redirect("/Files/Proyectos/" + nombre_proyecto + ".zip"); } catch (Exception) { /*Error*/} }
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { progressBar1.Value = 100; viewModel.IsRunning = false; if (Backup.OutputBackupFilePath != "") { var zip = new Ionic.Zip.ZipFile(); zip.UseUnicodeAsNecessary = true; //zip.AlternateEncoding = Encoding.UTF8; //zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed; zip.AddDirectory(Backup.TempFolderPath, null); zip.Save(Backup.OutputBackupFilePath); //zip.Dispose(); } }
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { this.BeginInvoke((MethodInvoker)delegate { this.progressBarX1.Value = 0; this.progressBarX1.Text = "Installing..."; this.progressBarX1.Refresh(); if (this.chkPerformBackup.Checked) { using (Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile()) { z.AddDirectory("c:\\program files\\openxcom"); z.Save(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\openxcom_backup.zip"); } } using (Ionic.Zip.ZipFile z = Ionic.Zip.ZipFile.Read(fullPath)) { foreach (Ionic.Zip.ZipEntry entry in z) { if (!entry.FileName.Contains("openxcom/UFO") && !entry.FileName.Contains("openxcom/TFTD")) { entry.Extract("c:\\program files", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); } } } MessageBox.Show("Installation Complete"); this.progressBarX1.Visible = false; }); }
private void OverwriteEpub(string file, string tempFile) { File.Delete(file); using (var zip = new Ionic.Zip.ZipFile()) { var mime = zip.AddEntry("mimetype", "application/epub+zip", Encoding.ASCII); zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Never; mime.CompressionLevel = Ionic.Zlib.CompressionLevel.None; mime.CompressionMethod = Ionic.Zip.CompressionMethod.None; var metaDir = Path.Combine(tempFile, "META-INF"); var meta = zip.AddDirectory(metaDir, "META-INF"); meta.CompressionLevel = Ionic.Zlib.CompressionLevel.None; var contentDir = Path.Combine(tempFile, "OEBPS"); var content = zip.AddDirectory(contentDir, "OEBPS"); content.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zip.Save(file); } directory.Delete(tempFile, true); }
/// <summary> /// Removes Rich signatures from all executable files inside XAP /// </summary> /// <param name="path"></param> /// <returns></returns> static bool RemoveSignaturesFromXap(string path) { /* cleaning up Temp folder */ string tempFolder = Path.Combine(Path.GetTempPath(), "RemoveRS"); if (!Directory.Exists(tempFolder)) Directory.CreateDirectory(tempFolder); string xapExtractionPath = Path.Combine(tempFolder, path.GetHashCode().ToString()); if (Directory.Exists(xapExtractionPath)) Directory.Delete(xapExtractionPath, true); Directory.CreateDirectory(xapExtractionPath); /* actual removing */ var zip = new Ionic.Zip.ZipFile(path); if (zip["/WMAppPRHeader.xml"] == null) { bool anythingChanged = false; bool resign = (zip["/AccountManager.dll"] != null) && (zip["/ComXapHandlerACM.dll"] != null); zip.ExtractAll(xapExtractionPath); var files = Directory.GetFiles(xapExtractionPath, "*.dll", SearchOption.AllDirectories); foreach (var file in files) { if (file.ToLower().EndsWith(".dll")) { anythingChanged |= RemoveSignature(file); if (resign) Sign(file); } } files = Directory.GetFiles(xapExtractionPath, "*.exe", SearchOption.AllDirectories); foreach (var file in files) { if (file.ToLower().EndsWith(".exe")) { anythingChanged |= RemoveSignature(file); if (resign) Sign(file); } } zip.Dispose(); if (anythingChanged) { zip = new Ionic.Zip.ZipFile(); zip.AddDirectory(xapExtractionPath); zip.Save(path); } return true; } else { zip.Dispose(); zip = null; } return false; }
/// <summary> /// 压缩文件夹,文件架下面包含文件夹 /// </summary> /// <param name="filePath">源文件夹路径</param> /// <param name="savePath">保存为Zip包的目录</param> public static void ZipDirInfo(string filePath, string savePath) { using (var zip = new ZipFile()) { zip.StatusMessageTextWriter = Console.Out; zip.AddDirectory(filePath, @"\"); zip.Save(savePath); } }