Example #1
0
        /// <summary>
        /// self compress a folder to a content
        /// </summary>
        /// <param name="outputFileName"></param>
        /// <param name="inputFolder"></param>
        /// <param name="resultCount"></param>
        /// <returns></returns>
        public bool CompressFolder(string outputFileName, string inputFolder, out int resultCount)
        {
            SevenZip.SevenZipCompressor cp = null;

            try
            {
                cp = new SevenZip.SevenZipCompressor();
                cp.ArchiveFormat = SevenZip.OutArchiveFormat.Zip;

                string[] outputFiles = new DirectoryInfo(inputFolder).GetFiles("*.*").Select(p => p.FullName).ToArray();

                using (FileStream fs = new FileStream(outputFileName, FileMode.Create))
                {
                    cp.CompressFiles(fs, outputFiles);
                }

                resultCount = outputFiles.Count();
                return(true);
            }
            catch (Exception err)
            {
                resultCount = 0;
                return(false);
            }
            finally
            {
                cp = null;
            }
        }
Example #2
0
        public static byte[] CreateWrappedArchive(string basePath, string[] includes, string[] excludes)
        {
            using (MemoryStream inStream = new MemoryStream()) {
                var zipOut = new SevenZipCompressor();
                zipOut.ArchiveFormat = OutArchiveFormat.Zip;
                zipOut.CompressionLevel = SevenZip.CompressionLevel.None;

                List<string> FileList = new List<string>(Search.FindFiles(
                    basePath, includes, excludes, SearchOption.AllDirectories
                ));

                SevenZipBase.SetLibraryPath(Inits.EnsureBinaries());
                zipOut.CompressFileDictionary(
                    FileList.ToDictionary(f => f.Replace(basePath, null), f => f),
                    inStream
                );

                inStream.Position = 0;

                using (var outStream = new MemoryStream()) {
                    using (var LzmaStream = new LzmaEncodeStream(outStream)) {
                        int byt = 0;
                        while ((byt = inStream.ReadByte()) != -1)
                            LzmaStream.WriteByte((byte)byt);
                    }
                    return outStream.ToArray();
                }
            }
        }
        public bool Zipp(IEnumerable<string> iText, string iFileName, string iPassword)
        {
            CheckArguments(iText, iFileName);

            SevenZipCompressor sevenZipCompressor = new SevenZipCompressor()
            {
                DirectoryStructure = true,
                EncryptHeaders = true,
                DefaultItemName = "Default.txt"
            };

            try
            {
                using (var instream = new MemoryStream())
                {
                    using (var streamwriter = new StreamWriter(instream) { AutoFlush = true })
                    {
                        iText.Apply(t => streamwriter.WriteLine(t));
                        instream.Position = 0;
                        using (Stream outstream = File.Create(iFileName))
                        {
                            sevenZipCompressor.CompressStream(instream, outstream, iPassword);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(string.Format("Problem zipping a text: {0}", e));
                return false;
            }

            return true;
        }
		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"));
		}
Example #5
0
 public void Compress(string sourceFilename, string targetFilename, FileMode fileMode, OutArchiveFormat archiveFormat,
     CompressionMethod compressionMethod, CompressionLevel compressionLevel, ZipEncryptionMethod zipEncryptionMethod,
     string password, int bufferSize, int preallocationPercent, bool check, Dictionary<string, string> customParameters)
 {
     bufferSize *= this._sectorSize;
     SevenZipCompressor compressor = new SevenZipCompressor();
     compressor.FastCompression = true;
     compressor.ArchiveFormat = archiveFormat;
     compressor.CompressionMethod = compressionMethod;
     compressor.CompressionLevel = compressionLevel;
     compressor.DefaultItemName = Path.GetFileName(sourceFilename);
     compressor.DirectoryStructure = false;
     compressor.ZipEncryptionMethod = zipEncryptionMethod;
     foreach (var pair in customParameters)
     {
         compressor.CustomParameters[pair.Key] = pair.Value;
     }
     using (FileStream sourceFileStream = new FileStream(sourceFilename,
         FileMode.Open, FileAccess.Read, FileShare.None, bufferSize,
         Win32.FileFlagNoBuffering | FileOptions.SequentialScan))
     {
         using (FileStream targetFileStream = new FileStream(targetFilename,
                fileMode, FileAccess.ReadWrite, FileShare.ReadWrite, 8,
                FileOptions.WriteThrough | Win32.FileFlagNoBuffering))
         {
             this.Compress(compressor, sourceFileStream, targetFileStream,
                 password, preallocationPercent, check, bufferSize);
         }
     }
 }
Example #6
0
 private void b_Compress_Click(object sender, EventArgs e)
 {
     SevenZipCompressor.SetLibraryPath(@"C:\Program Files\7-Zip\7z.dll");
     SevenZipCompressor cmp = new SevenZipCompressor();
     cmp.Compressing += new EventHandler<ProgressEventArgs>(cmp_Compressing);
     cmp.FileCompressionStarted += new EventHandler<FileNameEventArgs>(cmp_FileCompressionStarted);
     cmp.CompressionFinished += new EventHandler<EventArgs>(cmp_CompressionFinished);
     cmp.ArchiveFormat = (OutArchiveFormat)Enum.Parse(typeof(OutArchiveFormat), cb_Format.Text);
     cmp.CompressionLevel = (CompressionLevel)trb_Level.Value;
     cmp.CompressionMethod = (CompressionMethod)cb_Method.SelectedIndex;
     cmp.VolumeSize = chb_Volumes.Checked ? (int)nup_VolumeSize.Value : 0;
     string directory = tb_CompressDirectory.Text;
     string archFileName = tb_CompressOutput.Text;
     bool sfxMode = chb_Sfx.Checked;
     if (!sfxMode)
     {
         cmp.BeginCompressDirectory(directory, archFileName);
     }
     else
     {
         // Build SevenZipSharp with SFX
         /*SevenZipSfx sfx = new SevenZipSfx();
         using (MemoryStream ms = new MemoryStream())
         {
             cmp.CompressDirectory(directory, ms);
             sfx.MakeSfx(ms, archFileName.Substring(0, archFileName.LastIndexOf('.')) + ".exe");
         }*/
     }
 }
        private SevenZip.SevenZipCompressor CreateCompressor()
        {
            var compressor = new SevenZip.SevenZipCompressor();

            switch (ArchiveFormat)
            {
            case OutArchiveFormat.SevenZip:
                compressor.CompressionMethod = CompressionMethod.Lzma2;
                break;

            case OutArchiveFormat.Zip:
                compressor.CompressionMethod = CompressionMethod.Lzma;
                break;

            //case OutArchiveFormat.GZip:
            //    break;
            //case OutArchiveFormat.BZip2:
            //    break;
            //case OutArchiveFormat.Tar:
            //    break;
            //case OutArchiveFormat.XZ:
            //    break;
            default:
                // どうせ使わんし対応が面倒なので
                throw new NotImplementedException($"{ArchiveFormat}方式の圧縮は未対応です。");
            }
            compressor.ArchiveFormat         = ArchiveFormat;
            compressor.PreserveDirectoryRoot = false;
            compressor.CompressionLevel      = CompressionLevel.Ultra;

            return(compressor);
        }
 public static void CompressDirectory(string compressDirectory, string archFileName, OutArchiveFormat archiveFormat, CompressionLevel compressionLevel)
 {
     SevenZipCompressor.SetLibraryPath(LibraryPath);
     SevenZipCompressor cmp = new SevenZipCompressor();
     cmp.ArchiveFormat = archiveFormat;
     cmp.CompressionLevel = compressionLevel;
     cmp.BeginCompressDirectory(compressDirectory, archFileName);
 }
        /// <summary>
        /// Compresses files using gzip format
        /// </summary>
        /// <param name="files">The files.</param>
        /// <param name="destination">The destination.</param>
        public static void GZipFiles(string[] files, string destination)
        {
            SetupZlib();

            SevenZipCompressor compressor = new SevenZipCompressor();
            compressor.ArchiveFormat = OutArchiveFormat.GZip;
            compressor.CompressFiles(destination, files);
        }
Example #10
0
 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);
 }
Example #11
0
 public static void ZipFiles(string archivePath, params string[] targetFilesPath)
 {
     var compressor = new SevenZipCompressor();
     compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
     compressor.CompressionMode = CompressionMode.Create;
     compressor.TempFolderPath = System.IO.Path.GetTempPath();
     //compressor.CompressDirectory(source, output);
     compressor.CompressFiles(archivePath, targetFilesPath);
 }
Example #12
0
 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);
 }
		public void SerializationDemo(){
			ArgumentException ex = new ArgumentException("blahblah");
			System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
				new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			using (MemoryStream ms = new MemoryStream()) {
				bf.Serialize(ms, ex);
				SevenZipCompressor cmpr = new SevenZipCompressor();
				cmpr.CompressStream(ms, File.Create(createTempFileName()));
			}
		}
        public void packToZip(String filePathArchive, String romFolder)
        {
            if(!Directory.Exists(tempPath)){
                Directory.CreateDirectory(tempPath);
            }

            archivePacker = new SevenZipCompressor(tempFolder);

            archivePacker.ArchiveFormat = OutArchiveFormat.Zip;
            archivePacker.BeginCompressDirectory(romFolder, filePathArchive, "");
        }
Example #15
0
 private void Compress(string directory, string archFileName)
 {
     SevenZipCompressor.SetLibraryPath(AppDomain.CurrentDomain.BaseDirectory + "7z.dll");
     SevenZipCompressor cmp = new SevenZipCompressor();
     cmp.Compressing += new EventHandler<ProgressEventArgs>(cmp_Compressing);
     cmp.FileCompressionStarted += new EventHandler<FileNameEventArgs>(cmp_FileCompressionStarted);
     cmp.CompressionFinished += new EventHandler<EventArgs>(cmp_CompressionFinished);
     cmp.ArchiveFormat = OutArchiveFormat.SevenZip;
     cmp.CompressionLevel = CompressionLevel.Normal;
     cmp.BeginCompressDirectory(directory, archFileName);
 }
Example #16
0
 static public void compress(string source, string outputFileName) {
     if (source != null && outputFileName != null) {
         SevenZipCompressor.SetLibraryPath("7z.dll");
         SevenZipCompressor cmp = new SevenZipCompressor();
         cmp.Compressing += new EventHandler<ProgressEventArgs>(cmp_Compressing);
         cmp.FileCompressionStarted += new EventHandler<FileNameEventArgs>(cmp_FileCompressionStarted);
         cmp.CompressionFinished += new EventHandler<EventArgs>(cmp_CompressionFinished);
         cmp.ArchiveFormat = (OutArchiveFormat)Enum.Parse(typeof(OutArchiveFormat), "SevenZip");
         cmp.CompressFiles(outputFileName, source);
     }
 }
Example #17
0
        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"));
        }
Example #18
0
 private void b_Compress_Click(object sender, RoutedEventArgs e)
 {
     SevenZipCompressor.SetLibraryPath(@"C:\Program Files\7-Zip\7z.dll");
     SevenZipCompressor cmp = new SevenZipCompressor();
     cmp.Compressing += new EventHandler<ProgressEventArgs>(cmp_Compressing);
     cmp.FileCompressionStarted += new EventHandler<FileNameEventArgs>(cmp_FileCompressionStarted);
     cmp.CompressionFinished += new EventHandler<EventArgs>(cmp_CompressionFinished);
     cmp.ArchiveFormat = (OutArchiveFormat)Enum.Parse(typeof(OutArchiveFormat), cb_Format.Text);
     cmp.CompressionLevel = (CompressionLevel)slider_Level.Value;
     string directory = tb_CompressFolder.Text;
     string archFileName = tb_CompressArchive.Text;
     cmp.BeginCompressDirectory(directory, archFileName);
 }
Example #19
0
        public static void SevenZIP(List<string> files, string output)
        {
            SevenZipExtractor.SetLibraryPath(ConfigurationManager.AppSettings["7ZIPDLL"]);

            SevenZipCompressor.SetLibraryPath(ConfigurationManager.AppSettings["7ZIPDLL"]);

            SevenZipCompressor compressor = new SevenZipCompressor();
            compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
            compressor.CompressionMode = CompressionMode.Create;
            compressor.TempFolderPath = System.IO.Path.GetTempPath();
            //compressor.VolumeSize = 51200000;//50 MB
            compressor.CompressFiles(output, files.ToArray());
        }
Example #20
0
 protected override void ExecuteCore()
 {
     SevenZipCompressor compressor = null;
     try
     {
         var files = this.GetAllSources().ToList();
         foreach (var file in files) FileHelper.WaitForReady(FileHelper.GetDataFilePath(file));
         long nextLength = 0, nextFile = 0;
         FileLength = files.Sum(file => new FileInfo(FileHelper.GetFilePath(file)).Length);
         compressor = new SevenZipCompressor
         {
             CompressionLevel = (CompressionLevel)Enum.Parse(typeof(CompressionLevel),
                 TaskXml.GetAttributeValue("compressionLevel"), true)
         };
         switch (Path.GetExtension(RelativePath).ToLowerInvariant())
         {
             case ".7z":
                 compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
                 break;
             case ".zip":
                 compressor.ArchiveFormat = OutArchiveFormat.Zip;
                 break;
             case ".tar":
                 compressor.ArchiveFormat = OutArchiveFormat.Tar;
                 break;
         }
         var filesStart = Path.GetFullPath(FileHelper.GetFilePath(string.Empty)).Length + 1;
         compressor.FileCompressionStarted += (sender, e) =>
         {
             ProcessedSourceCount += nextFile;
             ProcessedFileLength += nextLength;
             nextFile = 1;
             nextLength = new FileInfo(e.FileName).Length;
             CurrentSource = e.FileName.Substring(filesStart);
             Save();
         };
         compressor.CompressFiles(FileHelper.GetFilePath(RelativePath),
             Path.GetFullPath(FileHelper.GetFilePath(BaseFolder)).Length + 1,
             files.Select(file => Path.GetFullPath(FileHelper.GetFilePath(file))).ToArray());
         ProcessedSourceCount += nextFile;
         ProcessedFileLength += nextLength;
         Finish();
     }
     catch (SevenZipException)
     {
         if (compressor == null) throw;
         throw new AggregateException(compressor.Exceptions);
     }
 }
        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";
        }
Example #22
0
        public int Compress(PointCloudTile tile, byte[] uncompressedBuffer, int count, byte[] compressedBuffer)
        {
            SevenZipCompressor compressor = new SevenZipCompressor
            {
                CompressionMethod = SevenZip.CompressionMethod.Lzma2,
                CompressionLevel = CompressionLevel.Fast
            };

            MemoryStream uncompressedStream = new MemoryStream(uncompressedBuffer, 0, count, false);

            // custom stream is required because the position is always 32 instead of the end of the stream
            MemorableMemoryStream compressedStream = new MemorableMemoryStream(compressedBuffer);

            compressor.CompressStream(uncompressedStream, compressedStream);

            return (int)compressedStream.MaxPosition;
        }
Example #23
0
 /// <summary>
 /// Compresses a directory into a single archive
 /// </summary>
 /// <param name="inDir">The path to the directory to compress</param>
 /// <param name="outFile">The archive name to create</param>
 /// <param name="notify">Flag to notify user when finished</param>
 public static void CompressDirectory(string inDir, string outFile, bool notify = false)
 {
     SevenZipBase.SetLibraryPath(PathHelper.SevenZipLibrary);
     if (_compressor == null)
     {
         _compressor = new SevenZipCompressor
         {
             ArchiveFormat = OutArchiveFormat.SevenZip,
             CompressionLevel = CompressionLevel.Ultra,
             CompressionMode = CompressionMode.Create
         };
     }
     _notify = notify;
     _compressor.TempFolderPath = Path.GetTempPath();
     _compressor.CompressDirectory(inDir, outFile);
     File.SetCreationTime(outFile, DateTime.Now);
 }
Example #24
0
 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); //сам процесс сжатия
     }
 }
 /// <summary>
 /// Creates a cache file for the given mod, containing the specified files.
 /// </summary>
 /// <param name="p_modMod">The mod for which to create the cache file.</param>
 /// <param name="p_strFilesToCacheFolder">The folder containing the files to put into the cache.</param>
 /// <returns>The cache file for the specified mod, or <c>null</c>
 /// if there were no files to cache.</returns>
 public Archive CreateCacheFile(IMod p_modMod, string p_strFilesToCacheFolder)
 {
     if (!String.IsNullOrEmpty(p_strFilesToCacheFolder))
     {
         string[] strFilesToCompress = Directory.GetFiles(p_strFilesToCacheFolder, "*.*", SearchOption.AllDirectories);
         if (strFilesToCompress.Length > 0)
         {
             string strCachePath = GetCacheFilePath(p_modMod);
             SevenZipCompressor szcCompressor = new SevenZipCompressor();
             szcCompressor.ArchiveFormat = OutArchiveFormat.Zip;
             szcCompressor.CompressionLevel = CompressionLevel.Ultra;
             szcCompressor.CompressDirectory(p_strFilesToCacheFolder, strCachePath);
             return new Archive(strCachePath);
         }
     }
     return null;
 }
Example #26
0
        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));

            }
        }
Example #27
0
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="input">字节数组</param>
        /// <returns>压缩后的字节数组</returns>
        public static byte[] Compress(byte[] input)
        {
            byte[] compressed = null;
            SevenZipCompressor compressor = new SevenZipCompressor();
            compressor.CompressionMethod = CompressionMethod.Ppmd;
            compressor.CompressionLevel = CompressionLevel.High;
            using (MemoryStream ms = new MemoryStream(input))
            {
                using (MemoryStream outMs = new MemoryStream())
                {
                    compressor.CompressStream(ms, outMs);
                    outMs.Position = 0;
                    compressed = new byte[outMs.Length];
                    outMs.Read(compressed, 0, compressed.Length);
                }
            }

            return compressed;
        }
Example #28
0
        public void Build(Package package, string path)
        {
            var archiveName = package.Manifest.Name.ToLowerInvariant().Replace(" ", "-") + "-v" + package.Manifest.Version;
            var archive = Path.Combine(FilePaths.PackageRepository, archiveName) + FileTypes.Package;

            var file = new FileInfo(Assembly.GetExecutingAssembly().Location);

            SevenZipCompressor.SetLibraryPath(Path.Combine(file.DirectoryName, "7z.dll"));

            var sevenZipCompressor = new SevenZipCompressor
                {
                    ArchiveFormat = OutArchiveFormat.SevenZip,
                    CompressionLevel = CompressionLevel.Ultra
                };

            sevenZipCompressor.Compressing += this.Compressing;
            sevenZipCompressor.CompressionFinished += this.CompressingFinished;

            sevenZipCompressor.CompressFiles(archive, package.Manifest.Files.Select(manifestFile => manifestFile.File).ToArray());
        }
Example #29
0
        internal string FirstSaveDynamicBook(Book bk)
        {
            try
            {
                // create a temp folder
                string tempFolder = DirectoryHelper.Combine(CBRFolders.Temp, Path.GetFileNameWithoutExtension(bk.FilePath));
                DirectoryHelper.Check(tempFolder);

                //extract the book content
                ExtractBook(bk, tempFolder);

                //serialize all frames even empty to create the files in the zip
                foreach (Page pg in bk.Pages)
                {
                    XmlHelper.Serialize(Path.Combine(tempFolder, pg.FileName + ".dynamics.xml"), pg.Frames.ToList());
                }

                // create a new file by compressing all temp folder content
                string newComic = bk.FilePath.Replace(Path.GetExtension(bk.FilePath), ".dcb");

                SevenZip.SevenZipCompressor cp = new SevenZip.SevenZipCompressor();
                cp.ArchiveFormat = SevenZip.OutArchiveFormat.Zip;

                string[] outputFiles = new DirectoryInfo(tempFolder).GetFiles("*.*").Select(p => p.FullName).ToArray();

                using (FileStream fs = new FileStream(newComic, FileMode.Create))
                {
                    cp.CompressFiles(fs, outputFiles);
                }

                //delete the temp folder
                Directory.Delete(tempFolder, true);

                return(newComic);
            }
            catch (Exception err)
            {
                LogHelper.Manage("BookService:FirstSaveDynamicBook", err);
            }
            return(null);
        }
Example #30
0
		public static byte[] CompressBytes(byte[] data)
	    {
	        byte[] compressedData = null;
	
	        SevenZipCompressor compressor = new SevenZipCompressor();
	        compressor.CompressionMethod = CompressionMethod.Ppmd;
	        compressor.CompressionLevel = SevenZip.CompressionLevel.Ultra;
	        compressor.ScanOnlyWritable = true;
	        compressor.DefaultItemName = "T";
	
	        using (MemoryStream msin = new MemoryStream(data))
	        {
	            using (MemoryStream msout = new MemoryStream())
	            {
	                compressor.CompressStream(msin, msout);	
	                compressedData = msout.ToArray();
	            }
	        }
	
	        return compressedData;
	    }
Example #31
0
        public static byte[] CompressBytes(byte[] data,
            CompressionLevel CompressionLevel,
            CompressionMethod CompressionMethod = CompressionMethod.Default
            )
        {
            Inits.EnsureBinaries();

            using (var inStream = new MemoryStream(data))
            {
                using (var outStream = new MemoryStream())
                {
                    var compressor = new SevenZipCompressor();
                    compressor.CompressionLevel = (SevenZip.CompressionLevel)(int)CompressionLevel;
                    compressor.CompressionMethod = (SevenZip.CompressionMethod)(int)CompressionMethod;
                    compressor.ScanOnlyWritable = true;
                    compressor.CompressStream(inStream, outStream);

                    return outStream.ToArray();
                }
            }
        }
Example #32
0
        public int compressArchive(Dictionary<string, Stream> files, string outFileName)
        {
            // create output archive
            SevenZipCompressor compressor = new SevenZipCompressor();
            try
            {
                var dict = new Dictionary<string, Stream>();

                foreach (var fileName in files.Keys)
                    dict.Add(fileName, files[fileName]);
                compressor.CompressStreamDictionary(dict, outFileName);
                return 0;

            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error: Could not create output archive: " + outFileName);

                Console.Error.WriteLine("\t" + ex.Message);
                return 1;
            }
        }
 /// <summary>
 /// Initializes a new instance of the ArchiveUpdateCallback class
 /// </summary>
 /// <param name="streamDict">Dictionary&lt;file stream, name of the archive entry&gt;</param>
 /// <param name="compressor">The owner of the callback</param>
 /// <param name="updateData">The compression parameters.</param>
 /// <param name="directoryStructure">Preserve directory structure.</param>
 public ArchiveUpdateCallback(
     IDictionary <string, Stream> streamDict,
     SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
 {
     Init(streamDict, compressor, updateData, directoryStructure);
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the ArchiveUpdateCallback class
 /// </summary>
 /// <param name="files">Array of files to pack</param>
 /// <param name="rootLength">Common file names root length</param>
 /// <param name="compressor">The owner of the callback</param>
 /// <param name="updateData">The compression parameters.</param>
 /// <param name="directoryStructure">Preserve directory structure.</param>
 public ArchiveUpdateCallback(
     FileInfo[] files, int rootLength,
     SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
 {
     Init(files, rootLength, compressor, updateData, directoryStructure);
 }
Example #35
0
        private void Deployment_BackgroundThread(object sender, DoWorkEventArgs e)
        {
            var referencedFiles = ModBeingDeployed.GetAllRelativeReferences();

            string archivePath = e.Argument as string;
            //Key is in-archive path, value is on disk path
            var archiveMapping             = new Dictionary <string, string>();
            SortedSet <string> directories = new SortedSet <string>();

            foreach (var file in referencedFiles)
            {
                var path      = Path.Combine(ModBeingDeployed.ModPath, file);
                var directory = Directory.GetParent(path).FullName;
                if (directory.Length <= ModBeingDeployed.ModPath.Length)
                {
                    continue;                                                      //root file or directory.
                }
                directory = directory.Substring(ModBeingDeployed.ModPath.Length + 1);

                //nested folders with no folders
                var    relativeFolders    = directory.Split('\\');
                string buildingFolderList = "";
                foreach (var relativeFolder in relativeFolders)
                {
                    if (buildingFolderList != "")
                    {
                        buildingFolderList += @"\\";
                    }
                    buildingFolderList += relativeFolder;
                    if (directories.Add(buildingFolderList))
                    {
                        archiveMapping[buildingFolderList] = null;
                    }
                }
            }

            archiveMapping.AddRange(referencedFiles.ToDictionary(x => x, x => Path.Combine(ModBeingDeployed.ModPath, x)));

            var compressor = new SevenZip.SevenZipCompressor();

            //compressor.CompressionLevel = CompressionLevel.Ultra;
            compressor.CustomParameters.Add(@"s", @"on");
            if (!MultithreadedCompression)
            {
                compressor.CustomParameters.Add(@"mt", @"off");
            }
            compressor.CustomParameters.Add(@"yx", @"9");
            //compressor.CustomParameters.Add("x", "9");
            compressor.CustomParameters.Add(@"d", @"28");
            string currentDeploymentStep = M3L.GetString(M3L.string_mod);

            compressor.Progressing += (a, b) =>
            {
                //Debug.WriteLine(b.AmountCompleted + "/" + b.TotalAmount);
                ProgressMax   = b.TotalAmount;
                ProgressValue = b.AmountCompleted;
                var now = DateTime.Now;
                if ((now - lastPercentUpdateTime).Milliseconds > ModInstaller.PERCENT_REFRESH_COOLDOWN)
                {
                    //Don't update UI too often. Once per second is enough.
                    string percent = (ProgressValue * 100.0 / ProgressMax).ToString(@"0.00");
                    OperationText         = $@"[{currentDeploymentStep}] {M3L.GetString(M3L.string_deploymentInProgress)} {percent}%";
                    lastPercentUpdateTime = now;
                }
                //Debug.WriteLine(ProgressValue + "/" + ProgressMax);
            };
            compressor.FileCompressionStarted += (a, b) => { Debug.WriteLine(b.FileName); };
            compressor.CompressFileDictionary(archiveMapping, archivePath);
            compressor.CustomParameters.Clear(); //remove custom params as it seems to force LZMA
            compressor.CompressionMode  = CompressionMode.Append;
            compressor.CompressionLevel = CompressionLevel.None;
            currentDeploymentStep       = @"moddesc.ini";
            compressor.CompressFiles(archivePath, new string[]
            {
                Path.Combine(ModBeingDeployed.ModPath, @"moddesc.ini")
            });
            OperationText = M3L.GetString(M3L.string_deploymentSucceeded);
            Utilities.HighlightInExplorer(archivePath);
        }
 /// <summary>
 /// Initializes a new instance of the ArchiveUpdateCallback class
 /// </summary>
 /// <param name="stream">The input stream</param>
 /// <param name="compressor">The owner of the callback</param>
 /// <param name="updateData">The compression parameters.</param>
 /// <param name="directoryStructure">Preserve directory structure.</param>
 public ArchiveUpdateCallback(
     Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
 {
     Init(stream, compressor, updateData, directoryStructure);
 }
Example #37
-1
        public static bool Export(string exportPath)
        {
            try
            {
                Set7ZipLibraryPath();

                SevenZipCompressor zip = new SevenZipCompressor();
                zip.ArchiveFormat = OutArchiveFormat.SevenZip;
                zip.CompressionLevel = CompressionLevel.Normal;
                zip.CompressionMethod = CompressionMethod.Lzma2;

                Dictionary<string, string> files = new Dictionary<string, string>();
                if (Program.Settings.ExportSettings)
                {
                    AddFileToDictionary(files, Program.ApplicationConfigFilePath);
                    AddFileToDictionary(files, Program.HotkeysConfigFilePath);
                    AddFileToDictionary(files, Program.UploadersConfigFilePath);
                    AddFileToDictionary(files, Program.GreenshotImageEditorConfigFilePath);
                }

                if (Program.Settings.ExportHistory)
                {
                    AddFileToDictionary(files, Program.HistoryFilePath);
                }

                if (Program.Settings.ExportLogs)
                {
                    foreach (string file in Directory.GetFiles(Program.LogsFolder, "*.txt", SearchOption.TopDirectoryOnly))
                    {
                        AddFileToDictionary(files, file, Path.GetFileName(Program.LogsFolder));
                    }
                }

                zip.CompressFileDictionary(files, exportPath);

                return true;
            }
            catch (Exception e)
            {
                DebugHelper.WriteException(e);
                MessageBox.Show("Error while exporting backup:\r\n\r\n" + e, "ShareX - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }