public void CompressionTestsVerySimple(){ var tmp = new SevenZipCompressor(); //tmp.ScanOnlyWritable = true; //tmp.CompressFiles(@"d:\Temp\arch.7z", @"d:\Temp\log.txt"); //tmp.CompressDirectory(@"c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\1033", @"D:\Temp\arch.7z"); tmp.CompressDirectory(testFold1, Path.Combine(tempFolder, TestContext.TestName + ".7z")); }
public static void ZipFolder(string archivePath, string targetDir) { var compressor = new SevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.SevenZip; compressor.CompressionMode = CompressionMode.Create; compressor.TempFolderPath = System.IO.Path.GetTempPath(); compressor.CompressDirectory(targetDir, archivePath); }
public void Pack(string outputPath) { SevenZipCompressor tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += new EventHandler<FileInfoEventArgs>((s, e) => { Console.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.Name)); }); tmp.CompressDirectory(_targetPath, outputPath, OutArchiveFormat.SevenZip); }
private static void Compress(string savePath, string backupPath, CompressionLevel compressionLevel = CompressionLevel.None) { SevenZipCompressor compressor = new SevenZipCompressor(); compressor.CustomParameters.Add("mt", "on"); compressor.CompressionLevel = compressionLevel; compressor.ScanOnlyWritable = true; if (!Directory.Exists(backupPath)) Directory.CreateDirectory(backupPath); compressor.CompressDirectory(savePath, (Path.Combine(backupPath, GetTimeStamp()) + ".7z")); }
public string CreatePackage() { // Create the package file if (File.Exists(InstallPerpParms.FileLocation.ToString() + "\\profile.cfg") == true) { File.Delete(InstallPerpParms.FileLocation.ToString() + "\\profile.cfg"); } File.Create(InstallPerpParms.FileLocation.ToString() + "\\profile.cfg").Close(); using( StreamWriter ProfileStream = new StreamWriter(InstallPerpParms.FileLocation.ToString() + "\\profile.cfg")) { ProfileStream.WriteLine("GameName=" + PackageFile.GameName); ProfileStream.WriteLine("GameDir=" + PackageFile.GameDir.ToString()); ProfileStream.WriteLine("CurrentVersion=" + PackageFile.VersionNumber); ProfileStream.WriteLine("UpdateURL=" + PackageFile.UpdateURL.ToString()); ProfileStream.WriteLine("DescriptionURL=" + PackageFile.DescURL.ToString()); ProfileStream.WriteLine("GameType=" + PackageFile.TypeGame.ToString()); ProfileStream.WriteLine("LoginType=" + PackageFile.TypeLogin.ToString()); ProfileStream.WriteLine("CommandLineArgs=" + PackageFile.CommandLine); ProfileStream.Flush(); ProfileStream.Close(); } // create installer SevenZipSfx Installer = new SevenZipSfx(); SevenZipCompressor Compress = new SevenZipCompressor("C:\\Temp\\Compress"); // installer settings Dictionary<string, string> Settings = new Dictionary<string, string> { { "Title", PackageFile.GameName + " " + PackageFile.VersionNumber }, { "InstallPath", PackageFile.GameDir }, { "BeginPrompt", "Yükleme işlemi başlatılsın mı?" }, { "CancelPrompt", "Yükleme işlemi iptal edilecek?" }, { "OverwriteMode", "2" }, { "GUIMode", "1" }, { "ExtractDialogText", "Dosyalar ayıklanıyor" }, { "ExtractTitle", "Ayıklama İşlemi" }, { "ErrorTitle", "Hata!" } }; Compress.CompressDirectory(InstallPerpParms.FileLocation.ToString(), "c:\\temp\\compress.7zip"); Installer.ModuleFileName = Directory.GetCurrentDirectory() + "\\7zxSD_LZMA.sfx"; Installer.MakeSfx("c:\\temp\\compress.7zip", Settings, Directory.GetCurrentDirectory() + "\\" + InstallPerpParms.FileName); return "Done"; }
public override void Open() { string source_folder = @"D:\test"; //путь к папке, которую нужно поместить в архив string archive_name = "qwerty.zip"; //имя архива string library_source = "SevenZipSharp.dll"; //Путь к файлу 7zip.dll if (File.Exists(library_source)) //Если библиотека 7zip существует { SevenZipBase.SetLibraryPath(library_source); //Подгружаем библиотеку 7zip var compressor = new SevenZipCompressor(); //Объявляем переменную архиватора compressor.ArchiveFormat = OutArchiveFormat.SevenZip; //Выбираем формат архива compressor.CompressionLevel = CompressionLevel.Ultra; // ультра режим сжатия compressor.CompressionMode = CompressionMode.Create; //подтверждаются настройки compressor.TempFolderPath = System.IO.Path.GetTempPath();//объявляется временная папка compressor.CompressDirectory(source_folder, archive_name, false); //сам процесс сжатия } }
public void execute(MinecraftPaths p) { Regex zip = new Regex(@"ZIP$"); if (zip.IsMatch(target)) { SevenZip.SevenZipCompressor comp = new SevenZipCompressor(); Match m = zip.Match(target); target = target.Remove(m.Index) + "NAME"; comp.CompressDirectory(p.resolvePath(source, ExtraTags), p.resolvePath(target, ExtraTags)); } else { SMMMUtil.FileSystemUtils.CopyDirectory(p.resolvePath(source, ExtraTags), p.resolvePath(target, ExtraTags)); } }
/// <summary> /// Compresses the specified source folder into a mod file at the specified destination. /// </summary> /// <remarks> /// If the desitnation file exists, it will be overwritten. /// </remarks> /// <param name="p_strSourcePath">The folder to compress into a mod file.</param> /// <param name="p_strDestinationPath">The path of the mod file to create.</param> public override void Compress(string p_strSourcePath, string p_strDestinationPath) { Int32 intFileCount = Directory.GetFiles(p_strSourcePath).Length; SevenZipCompressor szcCompressor = new SevenZipCompressor(); szcCompressor.CompressionLevel = EnvironmentInfo.Settings.ModCompressionLevel; szcCompressor.ArchiveFormat = EnvironmentInfo.Settings.ModCompressionFormat; szcCompressor.CompressionMethod = CompressionMethod.Default; switch (szcCompressor.ArchiveFormat) { case OutArchiveFormat.Zip: case OutArchiveFormat.GZip: case OutArchiveFormat.BZip2: szcCompressor.CustomParameters.Add("mt", "on"); break; case OutArchiveFormat.SevenZip: case OutArchiveFormat.XZ: szcCompressor.CustomParameters.Add("mt", "on"); szcCompressor.CustomParameters.Add("s", "off"); break; } szcCompressor.CompressionMode = CompressionMode.Create; szcCompressor.FileCompressionStarted += new EventHandler<FileNameEventArgs>(Compressor_FileCompressionStarted); szcCompressor.CompressDirectory(p_strSourcePath, p_strDestinationPath); }
/// <param name="zip">Compressor.</param> /// <param name="path">Input directory.</param> /// <param name="name">Archive name.</param> protected virtual void compressDirectory(SevenZipCompressor zip, string path, string name) { zip.CompressDirectory(path, name); }
public static void Compress(string directory, string file) { var compressor = new SevenZipCompressor(); compressor.CompressDirectory(directory, file); }
public void Pack(string sourcePath, string destinationPath) { var skin = Path.Combine(sourcePath, "Skin.xml"); var cursorsDir = Path.Combine(sourcePath, "Cursors"); var fontsDir = Path.Combine(sourcePath, "Fonts"); var imagesDir = Path.Combine(sourcePath, "Images"); if (!File.Exists(skin) || !Directory.Exists(cursorsDir) || !Directory.Exists(fontsDir) || !Directory.Exists(imagesDir)) { logger.Error("Cursors, Fonts, Images and Skin.xml are required"); return; } logger.Info("Packing skin '{0}'", sourcePath); var tempDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "Gnomoria.ContentExtractor", Guid.NewGuid().ToString())).FullName; var skinRoot = Path.Combine(tempDir, "skinRoot"); Directory.CreateDirectory(skinRoot); logger.Debug("Packing Skin.xml"); using (var file = File.Create(Path.Combine(skinRoot, "Skin.xnb"))) using (var xml = File.OpenRead(skin)) { var header = SkinHeader.Split(' ') .Select(s => Convert.ToByte(s, 16)) .ToArray(); file.Write(header, 0, header.Length); xml.CopyTo(file); } logger.Debug("Packing images"); var images = Directory.GetFiles(imagesDir, "*.png", SearchOption.AllDirectories); var destination = Path.Combine(skinRoot, "Images"); PackSkinImages(images, imagesDir, destination, tempDir); logger.Debug("Copying fonts"); // since fonts arent unpacked by this tool, just copy the XNBs destination = Path.Combine(skinRoot, "Fonts"); var fonts = Directory.GetFiles(fontsDir, "*.xnb", SearchOption.AllDirectories); Directory.CreateDirectory(destination); foreach (var font in fonts) { var name = Path.GetFileNameWithoutExtension(font); File.Copy(font, Path.Combine(destination, name + ".xnb"), true); } logger.Debug("Copying cursors"); // since fonts arent unpacked by this tool, just copy the XNBs destination = Path.Combine(skinRoot, "Cursors"); var cursors = Directory.GetFiles(cursorsDir, "*.xnb", SearchOption.AllDirectories); Directory.CreateDirectory(destination); foreach (var cursor in cursors) { var name = Path.GetFileNameWithoutExtension(cursor); File.Copy(cursor, Path.Combine(destination, name + ".xnb"), true); } logger.Debug("Zipping skin contents"); var zipper = new SevenZipCompressor { PreserveDirectoryRoot = false, ArchiveFormat = OutArchiveFormat.Zip, CompressionLevel = CompressionLevel.Ultra, }; zipper.CompressDirectory(skinRoot, destinationPath, true); logger.Debug("Cleaning up temp files"); Directory.Delete(tempDir, true); }
/// <summary> /// A simple constructor that initializes the object. /// </summary> /// <param name="path">The path to the fomod file.</param> internal fomod(string path, bool p_booUseCache) { this.filepath = path; ModName = System.IO.Path.GetFileNameWithoutExtension(path); m_arcFile = new Archive(path); m_strCachePath = Path.Combine(Program.GameMode.ModInfoCacheDirectory, ModName + ".zip"); if (p_booUseCache && File.Exists(m_strCachePath)) m_arcCacheFile = new Archive(m_strCachePath); FindPathPrefix(); m_arcFile.FilesChanged += new EventHandler(Archive_FilesChanged); baseName = ModName.ToLowerInvariant(); Author = DEFAULT_AUTHOR; Description = Email = Website = string.Empty; HumanReadableVersion = DEFAULT_VERSION; MachineVersion = DefaultVersion; MinFommVersion = DefaultMinFommVersion; Groups = new string[0]; isActive = (InstallLog.Current.GetModKey(this.baseName) != null); //check for script for (int i = 0; i < FomodScript.ScriptNames.Length; i++) if (ContainsFile("fomod/" + FomodScript.ScriptNames[i])) { m_strScriptPath = "fomod/" + FomodScript.ScriptNames[i]; break; } //check for readme for (int i = 0; i < Readme.ValidExtensions.Length; i++) if (ContainsFile("readme - " + baseName + Readme.ValidExtensions[i])) { m_strReadmePath = "Readme - " + Path.GetFileNameWithoutExtension(path) + Readme.ValidExtensions[i]; break; } if (String.IsNullOrEmpty(m_strReadmePath)) for (int i = 0; i < Readme.ValidExtensions.Length; i++) if (ContainsFile("docs/readme - " + baseName + Readme.ValidExtensions[i])) { m_strReadmePath = "docs/Readme - " + Path.GetFileNameWithoutExtension(path) + Readme.ValidExtensions[i]; break; } //check for screenshot string[] extensions = new string[] { ".png", ".jpg", ".bmp" }; for (int i = 0; i < extensions.Length; i++) if (ContainsFile("fomod/screenshot" + extensions[i])) { m_strScreenshotPath = "fomod/screenshot" + extensions[i]; break; } if (p_booUseCache && !File.Exists(m_strCachePath) && (m_arcFile.IsSolid || m_arcFile.ReadOnly)) { string strTmpInfo = Program.CreateTempDirectory(); try { Directory.CreateDirectory(Path.Combine(strTmpInfo, GetPrefixAdjustedPath("fomod"))); if (ContainsFile("fomod/info.xml")) File.WriteAllBytes(Path.Combine(strTmpInfo, GetPrefixAdjustedPath("fomod/info.xml")), GetFileContents("fomod/info.xml")); else File.WriteAllText(Path.Combine(strTmpInfo, GetPrefixAdjustedPath("fomod/info.xml")), "<fomod/>"); if (!String.IsNullOrEmpty(m_strReadmePath)) File.WriteAllBytes(Path.Combine(strTmpInfo, GetPrefixAdjustedPath(m_strReadmePath)), GetFileContents(m_strReadmePath)); if (!String.IsNullOrEmpty(m_strScreenshotPath)) File.WriteAllBytes(Path.Combine(strTmpInfo, GetPrefixAdjustedPath(m_strScreenshotPath)), GetFileContents(m_strScreenshotPath)); string[] strFilesToCompress = Directory.GetFiles(strTmpInfo, "*.*", SearchOption.AllDirectories); if (strFilesToCompress.Length > 0) { SevenZipCompressor szcCompressor = new SevenZipCompressor(); szcCompressor.ArchiveFormat = OutArchiveFormat.Zip; szcCompressor.CompressionLevel = CompressionLevel.Ultra; szcCompressor.CompressDirectory(strTmpInfo, m_strCachePath); } } finally { FileUtil.ForceDelete(strTmpInfo); } if (File.Exists(m_strCachePath)) m_arcCacheFile = new Archive(m_strCachePath); } LoadInfo(); }
private void Compress() { //setup settings. try { _sevenZipCompressor = new SevenZipCompressor(tempPath); _sevenZipCompressor.ArchiveFormat = _format; _sevenZipCompressor.CompressionMethod = CompressionMethod.Default; _sevenZipCompressor.DirectoryStructure = true; _sevenZipCompressor.IncludeEmptyDirectories = true; _sevenZipCompressor.FastCompression = _fastcompression; _sevenZipCompressor.PreserveDirectoryRoot = false; _sevenZipCompressor.CompressionLevel = _compresstionlevel; _sevenZipCompressor.Compressing += Compressing; _sevenZipCompressor.FileCompressionStarted += FileCompressionStarted; _sevenZipCompressor.CompressionFinished += CompressionFinished; _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; try { if (_password != null) { for (int i = 0; i < _fileAndDirectoryFullPaths.Count; i++) { if (!Directory.Exists(_fileAndDirectoryFullPaths[i])) continue; //Compress directories var strings = _fileAndDirectoryFullPaths[i].Split('/'); if (_fileAndDirectoryFullPaths.Count == 1) { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format))); } else { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}_{3}.{2}", _archivePath, _archivename, SelectExtention(_format), _fileAndDirectoryFullPaths[i].Split('\\') .Last()), _password); } //remove the directorys from the list so they will not be compressed as files as wel _fileAndDirectoryFullPaths.Remove(_fileAndDirectoryFullPaths[i]); } //compress files if (_fileAndDirectoryFullPaths.Count > 0) { _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; _sevenZipCompressor.CompressFilesEncrypted( String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format)), _password, _fileAndDirectoryFullPaths.ToArray()); } } else { for (int i = 0; i < _fileAndDirectoryFullPaths.Count; i++) //var fullPath in _fileAndDirectoryFullPaths) { FileInfo fi = new FileInfo(_fileAndDirectoryFullPaths[i]); bytesoffiles += fi.Length; if (!Directory.Exists(_fileAndDirectoryFullPaths[i])) continue; //Compress directorys var strings = _fileAndDirectoryFullPaths[i].Split('/'); if (_fileAndDirectoryFullPaths.Count == 1) { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format))); } else { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}_{3}.{2}", _archivePath, _archivename, SelectExtention(_format), _fileAndDirectoryFullPaths[i].Split('\\') .Last())); } //reset compression bar //FileCompressionFinished(null, null); //remove the directorys from the list so they will not be compressed as files as wel _fileAndDirectoryFullPaths.Remove(_fileAndDirectoryFullPaths[i]); } //compress files. if (_fileAndDirectoryFullPaths.Count > 0) { _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; _sevenZipCompressor.CompressFiles( String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format)), _fileAndDirectoryFullPaths.ToArray()); } } pb_totaalfiles.Invoke(new InvokeNone(() => { pb_totaalfiles.Value = 100; })); Done(); } catch (ThreadInterruptedException) { Dispose(true); } } catch { /* var dialog = new TaskDialog(); dialog.StandardButtons = TaskDialogStandardButtons.Ok; dialog.Text = ex.Message; dialog.Show(); */ } }
public void StreamingCompressionTest(){ var tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += (s, e) =>{ //TestContext.WriteLine(String.Format("[{0}%] {1}",e.PercentDone, e.FileName)); }; tmp.CompressDirectory(testFold1, File.Create(Path.Combine(tempFolder, TestContext.TestName + ".7z"))); }
public async Task MultiTaskedCompressionTest(){ var t1 = Task.Factory.StartNew(() =>{ var tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName)); tmp.CompressDirectory(testFold1, Path.Combine(tempFolder, TestContext.TestName + "1.7z")); }); var t2 = Task.Factory.StartNew(() =>{ var tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName)); tmp.CompressDirectory(testFold2, Path.Combine(tempFolder, TestContext.TestName + "2.7z")); }); await Task.WhenAll(t1, t2); }
public void MultiThreadedCompressionTest(){ var t1 = new Thread(() =>{ var tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName)); tmp.CompressDirectory(testFold1, Path.Combine(tempFolder, TestContext.TestName + "1.7z")); }); var t2 = new Thread(() =>{ var tmp = new SevenZipCompressor(); tmp.FileCompressionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName)); tmp.CompressDirectory(testFold2, Path.Combine(tempFolder, TestContext.TestName + "2.7z")); }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); }
public void CompressionTestLotsOfFeatures(){ var tmp = new SevenZipCompressor(); tmp.ArchiveFormat = OutArchiveFormat.SevenZip; tmp.CompressionLevel = CompressionLevel.High; tmp.CompressionMethod = CompressionMethod.Ppmd; tmp.FileCompressionStarted += (s, e) =>{ if (e.PercentDone > 50) e.Cancel = true; else { //TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName)); } }; tmp.FilesFound += (se, ea) => { TestContext.WriteLine("Number of files: " + ea.Value.ToString()); }; var arch = Path.Combine(tempFolder, TestContext.TestName + ".ppmd.7z"); tmp.CompressFiles(arch, testFile1, testFile2); tmp.CompressDirectory(testFold1, arch); }
public void CompressionTestMultiVolumes(){ var tmp = new SevenZipCompressor(); tmp.VolumeSize = 10000; tmp.CompressDirectory(testFold1, Path.Combine(tempFolder, TestContext.TestName + ".7z")); }
/// <summary> /// Performs some work based on the settings passed. /// </summary> /// <param name="settings">The settings. These specify the settings that the plugin /// should use and normally contain key/value pairs of parameters.</param> /// <param name="lastPlugin">The last plugin run. This is often useful as /// normally, plugins need to work with the output produced from the last plugin.</param> public void Run(IPluginRuntimeSettings settings, IPlugin lastPlugin) { _runtimeSettings = settings ; string lastPath = lastPlugin.WorkingPath ; _workingPath = getPathToSaveZippedFileTo( settings, lastPath ) ; if(File.Exists( _workingPath )) { File.Delete( _workingPath ); } var compressor = new SevenZipCompressor(); SevenZipLibraryManager.LibraryFileName = Settings.PathTo7ZipBinary ; string password = getPasswordIfSpecified( settings ) ; if( Directory.Exists( lastPath )) { compressor.CompressDirectory( lastPath, _workingPath, OutArchiveFormat.SevenZip, password ); } else { compressor.CompressFiles( new[] { lastPath }, _workingPath, OutArchiveFormat.SevenZip, password ); } }
public override void Execute() { if (_cmdlet._directoryOrFilesFromPipeline == null) { _cmdlet._directoryOrFilesFromPipeline = new List<string> { _cmdlet.Path }; } var directoryOrFiles = _cmdlet._directoryOrFilesFromPipeline .Select(path => new FileInfo(System.IO.Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, path)).FullName).ToArray(); var archiveFileName = new FileInfo(System.IO.Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.ArchiveFileName)).FullName; switch (System.IO.Path.GetExtension(archiveFileName).ToLowerInvariant()) { case ".7z": _cmdlet.Format = OutArchiveFormat.SevenZip; break; case ".zip": _cmdlet.Format = OutArchiveFormat.Zip; break; case ".gz": _cmdlet.Format = OutArchiveFormat.GZip; break; case ".bz2": _cmdlet.Format = OutArchiveFormat.BZip2; break; case ".tar": _cmdlet.Format = OutArchiveFormat.Tar; break; case ".xz": _cmdlet.Format = OutArchiveFormat.XZ; break; } var compressor = new SevenZipCompressor { ArchiveFormat = _cmdlet.Format, CompressionLevel = _cmdlet.CompressionLevel, CompressionMethod = _cmdlet.CompressionMethod }; _cmdlet.CustomInitialization?.Invoke(compressor); var activity = directoryOrFiles.Length > 1 ? $"Compressing {directoryOrFiles.Length} Files to {archiveFileName}" : $"Compressing {directoryOrFiles.First()} to {archiveFileName}"; var currentStatus = "Compressing"; compressor.FilesFound += (sender, args) => Write($"{args.Value} files found for compression"); compressor.Compressing += (sender, args) => WriteProgress(new ProgressRecord(0, activity, currentStatus) { PercentComplete = args.PercentDone }); compressor.FileCompressionStarted += (sender, args) => { currentStatus = $"Compressing {args.FileName}"; Write($"Compressing {args.FileName}"); }; if (directoryOrFiles.Any(path => new FileInfo(path).Exists)) { var notFoundFiles = directoryOrFiles.Where(path => !new FileInfo(path).Exists).ToArray(); if (notFoundFiles.Any()) { throw new FileNotFoundException("File(s) not found: " + string.Join(", ", notFoundFiles)); } if (HasPassword) { compressor.CompressFiles(archiveFileName, directoryOrFiles); } else { compressor.CompressFilesEncrypted(archiveFileName, _cmdlet.Password, directoryOrFiles); } } if (directoryOrFiles.Any(path => new DirectoryInfo(path).Exists)) { if (directoryOrFiles.Length > 1) { throw new ArgumentException("Only one directory allowed as input"); } if (_cmdlet.Filter != null) { if (HasPassword) { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Password, _cmdlet.Filter, true); } else { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Filter, true); } } else { if (HasPassword) { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Password); } else { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName); } } } WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed }); Write("Compression finished"); }
/// <summary> /// Creates a fomod file at the given path from the given directory. /// </summary> /// <param name="p_strFomodFolder">The folder from which to create the fomod.</param> /// <param name="p_strPackedFomodPath">The path of the new fomod file to create.</param> protected void PackFomod(string p_strFomodFolder, string p_strPackedFomodPath) { ProgressDialog.ItemProgress = 0; ProgressDialog.ItemProgressMaximum = Directory.GetFiles(p_strFomodFolder, "*", SearchOption.AllDirectories).Length; ProgressDialog.ItemProgressStep = 1; ProgressDialog.ItemMessage = String.Format("Compressing FOMod..."); var szcCompressor = new SevenZipCompressor(); szcCompressor.CompressionLevel = Settings.Default.fomodCompressionLevel; szcCompressor.ArchiveFormat = Settings.Default.fomodCompressionFormat; szcCompressor.CompressionMethod = CompressionMethod.Default; switch (szcCompressor.ArchiveFormat) { case OutArchiveFormat.Zip: case OutArchiveFormat.GZip: case OutArchiveFormat.BZip2: szcCompressor.CustomParameters.Add("mt", "on"); break; case OutArchiveFormat.SevenZip: case OutArchiveFormat.XZ: szcCompressor.CustomParameters.Add("mt", "on"); szcCompressor.CustomParameters.Add("s", "off"); break; } szcCompressor.CompressionMode = CompressionMode.Create; szcCompressor.FileCompressionStarted += FileCompressionStarted; szcCompressor.FileCompressionFinished += FileCompressionFinished; szcCompressor.CompressDirectory(p_strFomodFolder, p_strPackedFomodPath); }
public void CompressWithCustomParametersDemo(){ var tmp = new SevenZipCompressor(); tmp.ArchiveFormat = OutArchiveFormat.Zip; tmp.CompressionMethod = CompressionMethod.Deflate; tmp.CompressionLevel = CompressionLevel.Ultra; //Number of fast bytes tmp.CustomParameters.Add("fb", "256"); //Number of deflate passes tmp.CustomParameters.Add("pass", "4"); //Multi-threading on tmp.CustomParameters.Add("mt", "on"); tmp.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; /*tmp.Compressing += (s, e) => { TestContext.Clear(); TestContext.WriteLine(String.Format("{0}%", e.PercentDone)); };*/ tmp.CompressDirectory(testFold1, Path.Combine(tempFolder, TestContext.TestName + ".7z"), "test"); /*SevenZipCompressor tmp = new SevenZipCompressor(); tmp.CompressionMethod = CompressionMethod.Ppmd; tmp.CompressionLevel = CompressionLevel.Ultra; tmp.EncryptHeadersSevenZip = true; tmp.ScanOnlyWritable = true; tmp.CompressDirectory(@"d:\Temp\!Пусто", @"d:\Temp\arch.7z", "test"); //*/ }
/// <summary> /// Compresses a file using the .zip format. /// </summary> /// <param name="sourceDir">The directory to compress.</param> /// <param name="fileName">The name of the archive to be created.</param> public static void ZipFile(string sourceDir, string fileName) { SetupZlib(); SevenZipCompressor compressor = new SevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.Zip; compressor.CompressDirectory(sourceDir, fileName); }
private void Task_ImportInvoices() { Objsearch oQuery = new Objsearch(); try { oQuery.OpenQBConnection(); m_oInvoice.OpenQBConnection(); List<SyncInvoice> oInvoices = this.m_oSyncInvoices.GetSelectedInvoices(); Directory.CreateDirectory(m_sDirectoryRoot); string sRootName = string.Format("{0:MM-dd-yyyy hhmmss}", DateTime.Now); string fullFileNameAndPath = string.Format(@"Uploads\{0}.7z", sRootName); m_iTotal = oInvoices.Count; m_iCurrent = 0; this._logger.DebugFormat("Invoices found for processing: {0}", oInvoices.Count); for (int i = 0; i < oInvoices.Count; i++) { this.ProcessInvoice(oInvoices[i]); } if (m_oListInvoices.Count > 0) { // Serialize invoice information string sInvoicesFilename = string.Format(@"{0}\Invoices.dat", m_sDirectoryRoot); this._logger.DebugFormat("Writing dat file: {0}", sInvoicesFilename); FileStream oFileStream = new FileStream(sInvoicesFilename, FileMode.Create); BinaryFormatter oFormatter = new BinaryFormatter(); oFormatter.Serialize(oFileStream, m_oListInvoices); oFileStream.Close(); this._logger.Debug("Dat file written"); // Create zipped file this._logger.DebugFormat("Zipping folder using: {0}", Path.Combine(Application.StartupPath, "7z.dll")); SevenZipCompressor.SetLibraryPath(Path.Combine(Application.StartupPath, "7z.dll")); SevenZipCompressor oCompressor = new SevenZipCompressor(); oCompressor.PreserveDirectoryRoot = true; oCompressor.IncludeEmptyDirectories = true; oCompressor.CompressDirectory(Path.Combine(Environment.CurrentDirectory, m_sDirectoryRoot), fullFileNameAndPath); this._logger.DebugFormat("Folder zipped: {0} {1}", Path.Combine(Environment.CurrentDirectory, m_sDirectoryRoot), fullFileNameAndPath); // Upload if (!m_oQuickbooks.Upload(fullFileNameAndPath)) { MessageBox.Show("Upload Error: " + m_oQuickbooks.Error); } else { if (this.DeleteInvoiceFolderAndZipFile) { File.Delete(fullFileNameAndPath); } } } m_oWorkerProcess.ReportProgress(100); } catch (Exception ex) { MessageBox.Show(string.Format("Error: {0} \n\n {1}", ex.Message, ex.StackTrace)); } finally { // Delete root directory, no longer need it if (Directory.Exists(m_sDirectoryRoot) && this.DeleteInvoiceFolderAndZipFile) { Directory.Delete(m_sDirectoryRoot, true); } m_oListInvoices.Clear(); oQuery.CloseQBConnection(); m_oInvoice.CloseQBConnection(); } }
public void DownloadCourse(string courseName, string destDir, bool reverse, bool gzipCourses, Course courseContent) { if (!courseContent.Weeks.Any()) { Console.WriteLine(" Warning: no downloadable content found for {0}, did you accept the honour code?", courseName); } else { Console.WriteLine(" * Got all downloadable content for {0} ", courseName); } if (reverse) { courseContent.Weeks.Reverse(); } //where the course will be downloaded to string courseDir = Path.Combine(destDir, courseName); //if (!Directory.Exists(courseDir)) //{ // Directory.CreateDirectory(courseDir); //} Console.WriteLine("* " + courseName + " will be downloaded to " + courseDir); //download the standard pages Console.WriteLine(" - Downloading lecture/syllabus pages"); //Download(string.Format(_edxCourse.HOME_URL, courseName), courseDir, "index.html"); //Download(string.Format(_edxCourse.LectureUrlFromName(courseName)), courseDir, "lectures.html"); //now download the actual content (video's, lecture notes, ...) foreach (Week week in courseContent.Weeks) { //TODO: filter /*if (Wk_filter && week.Key) { } * * if self.wk_filter and j not in self.wk_filter: print_(" - skipping %s (idx = %s), as it is not in the week filter" % (weeklyTopic, j)) continue */ //Filter the text stuff only // add a numeric prefix to the week directory name to ensure chronological ordering string wkdirname = week.WeekNum.ToString().PadLeft(2, '0') + " - " + week.WeekName; //ensure the week dir exists Console.WriteLine(" - " + week.WeekName); string wkdir = Path.Combine(courseDir, wkdirname); Directory.CreateDirectory(wkdir); foreach (ClassSegment classSegment in week.ClassSegments) { //ensure chronological ordering string clsdirname = classSegment.ClassName; //ensure the class dir exists string clsdir = Path.Combine(wkdir, clsdirname); clsdir = Utilities.TrimPathPart(clsdir, _edxCourse.Max_path_part_len - 15); Directory.CreateDirectory(clsdir); Console.WriteLine(" - Downloading resources for " + clsdirname); //download each resource foreach (KeyValuePair<string, string> resourceLink in classSegment.ResourceLinks) { //Filter here try { Download(resourceLink.Key, clsdir, resourceLink.Value); } catch (Exception e) { Console.WriteLine(" - failed: {0}, {1}", resourceLink.Key, e.Message); //throw e; } } } } if (gzipCourses) { SevenZipCompressor zipCompressor = new SevenZipCompressor(); zipCompressor.CompressDirectory(destDir, courseName + ".7z"); } }
public override bool BackupServer(SettingsLoader.ServerChild ServerData) { string BackupFrom = string.Format("{0}\\ShooterGame\\Saved\\", ServerData.GameServerPath); string BackupTo = ServerData.BackupDirectory; if( !Directory.Exists(BackupFrom) ) { _Parent.Log.ConsolePrint(LogLevel.Warning, @"Unable to Backup server, directory ShooterGame\Saved is missing. If this is the first startup then ignore this message"); return false; } else if( (BackupTo.Length <= 0) || !Directory.Exists(BackupTo) ) { _Parent.Log.ConsolePrint(LogLevel.Warning, @"Unable to Backup server, Specified backup directory does not exist or is not set."); return false; } _Parent.Log.ConsolePrint(LogLevel.Info, "Starting backup of server {0}", ServerData.GameServerName); if( _Parent.ARKConfiguration.Messages.ServerBackupBroadcast.Length >= 1 ) { using( var RCONClient = new ArkRCON("127.0.0.1", ServerData.RCONPort) ) { try { RCONClient.Authenticate(ServerData.ServerAdminPassword); RCONClient.ExecuteCommand(string.Format("serverchat {0}", _Parent.ARKConfiguration.Messages.ServerBackupBroadcast)); } catch( QueryException ) {} } } // Use 7zipSharp to compress the backup directory SevenZipCompressor.SetLibraryPath("7za.dll"); var Compressor = new SevenZipCompressor() { CompressionLevel = CompressionLevel.Normal, ArchiveFormat = OutArchiveFormat.SevenZip, IncludeEmptyDirectories = true, }; string BackupPath = string.Format("{0}\\Backup-{1}.7z", BackupTo, Helpers.CurrentUnixStamp); Compressor.CompressDirectory(BackupFrom, BackupPath); _Parent.Log.ConsolePrint(LogLevel.Success, "Backup of server {0} complete", ServerData.GameServerName); return true; }
public void CompressionTestFeaturesModifyMode(){ var arch = Path.Combine(tempFolder, TestContext.TestName + ".7z"); var tmp = new SevenZipCompressor(); tmp.CompressDirectory(testFold2, arch); tmp.ModifyArchive(arch, new Dictionary<int, string>(){{0, testFile1}}); //Delete //tmp.ModifyArchive(@"d:\Temp\test.7z", new Dictionary<int, string>() { { 19, null }, { 1, null } }); }
public override void Execute() { var path = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), Environment.Is64BitProcess ? "7z64.dll" : "7z.dll"); SevenZipBase.SetLibraryPath(path); var compressor = new SevenZipCompressor { ArchiveFormat = _cmdlet.Format, CompressionLevel = _cmdlet.CompressionLevel, CompressionMethod = _cmdlet.CompressionMethod }; var directory = Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.Directory); var fileName = Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.FileName); var activity = String.Format("Compressing {0} to {1}", directory, fileName); var currentStatus = "Compressing"; compressor.FilesFound += (sender, args) => Write(String.Format("{0} files found for compression", args.Value)); compressor.Compressing += (sender, args) => WriteProgress(new ProgressRecord(0, activity, currentStatus) { PercentComplete = args.PercentDone }); compressor.FileCompressionStarted += (sender, args) => { currentStatus = String.Format("Compressing {0}", args.FileName); Write(String.Format("Compressing {0}", args.FileName)); }; compressor.CompressDirectory(directory, fileName); WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed }); Write("Compression finished"); }
public static void Compress7z(string copyPath, Stream outStream, CompressionLevel compressionLevel) { SevenZipCompressor compressor = new SevenZipCompressor(); compressor.CustomParameters.Add("mt", "on"); compressor.CompressionLevel = compressionLevel; compressor.ScanOnlyWritable = true; compressor.CompressDirectory(copyPath, outStream); }
public void CompressionTestFeaturesAppendMode(){ var tmp = new SevenZipCompressor(); var arch = Path.Combine(tempFolder, TestContext.TestName + ".7z"); tmp.CompressDirectory(testFold2, arch); tmp.CompressionMode = CompressionMode.Append; tmp.CompressDirectory(testFold1, arch); tmp = null; }