示例#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;
            }
        }
示例#2
0
        /// <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);
        }
示例#3
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);
 }
示例#4
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);
     }
 }
示例#5
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());
        }
示例#6
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());
        }
示例#7
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);
        }
示例#8
0
            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");
            }
示例#9
0
 /// <param name="zip">Compressor.</param>
 /// <param name="name">Archive name.</param>
 /// <param name="input">Input files.</param>
 protected virtual void compressFiles(SevenZipCompressor zip, string name, params string[] input)
 {
     zip.CompressFiles(name, input); // -_-
 }
示例#10
0
		public void CompressFilesZipTest(){
			var tmp = new SevenZipCompressor();
			tmp.ArchiveFormat = OutArchiveFormat.Zip;
			tmp.CompressFiles(Path.Combine(tempFolder, TestContext.TestName + ".zip"), testFile1, testFile2);
		}
示例#11
0
		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);
		}
示例#12
0
        /// <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 );
            }
        }
示例#13
0
        /// <summary>
        /// Compresses a file using the .gz format.
        /// </summary>
        /// <param name="sourceFile">The file to compress.</param>
        /// <param name="fileName">The name of the archive to be created.</param>
        public static void GzipFile(string sourceFile, string fileName)
        {
            SetupZlib();

            SevenZipCompressor compressor = new SevenZipCompressor();
            compressor.ArchiveFormat = OutArchiveFormat.GZip;
            compressor.CompressFiles(fileName, sourceFile);
        }
        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 BuildFiles()
        {
            //check if the updatepath is set and if the directory exists.
            if (_updatePath != null && Directory.Exists(_updatePath))
            {
                //clear our the information
                _collections = new Collection();

                //asdasd
                if (!Directory.Exists(_updatePath + "\\output"))
                {
                    Directory.CreateDirectory(_updatePath+"\\output");
                }

                //get the directory information
                DirectoryInfo directory = new DirectoryInfo(_updatePath);

                //get the dir length
                int dirLength = _updatePath.Length;

                //run though each folder
                foreach (DirectoryInfo d in directory.GetDirectories())
                {
                    if (d.Name != "output")
                    {
                        //ask the collection to find the files
                        FileCollection c = FileCollection.Build(d);

                        //run though each files
                        foreach (FileItem f in c.Files)
                        {
                            //initiate a CRC object
                            CRC32 crc = new CRC32();

                            //build the stringname
                            string FullPath = _updatePath + "\\" + c.Name + f.Directory + f.Filename;

                            //write
                            Console.WriteLine("[FILE]          : " + FullPath);

                            //open a link to the file
                            using (Stream reader = new FileStream(FullPath, FileMode.Open, FileAccess.Read))
                            {
                                //go though each byte
                                foreach (byte b in crc.ComputeHash(reader))
                                {
                                    //build the crc string
                                    f.FileCRC += b.ToString("x2").ToLower();
                                }
                            }

                            //write
                            Console.WriteLine("[FILE-CRC]      : " + f.FileCRC);

                            //output file
                            string outputDir = _updatePath + "\\output" + f.Directory;
                            string outputFile = outputDir + f.Filename + ".7z";
                            Directory.CreateDirectory(outputDir);

                            //start archiving the file
                            SevenZipCompressor.SetLibraryPath("7z.dll");
                            SevenZipCompressor zip = new SevenZipCompressor();
                            zip.CompressionMethod = CompressionMethod.Lzma2;
                            zip.CompressionLevel = CompressionLevel.Ultra;
                            zip.CompressionMode = CompressionMode.Create;

                            Console.WriteLine("[COMPRESS-FROM] : " + FullPath);
                            Console.WriteLine("[COMPRESS-TO]   : " + outputDir + f.Filename + ".7z");
                            zip.CompressFiles(outputFile, FullPath);

                            //initiate a CRC object
                            CRC32 crc2 = new CRC32();

                            f.ArchiveCRC = "";

                            //open a link to the file
                            using (Stream reader = new FileStream(outputFile, FileMode.Open, FileAccess.Read))
                            {
                                //go though each byte
                                foreach (byte b in crc2.ComputeHash(reader))
                                {
                                    //build the crc string
                                    f.ArchiveCRC += b.ToString("x2").ToLower();
                                }
                            }
                            Console.WriteLine("[ARCHIVE-CRC]   : " + f.ArchiveCRC);

                            Console.WriteLine();
                        }

                        //add the collection to the group
                        _collections.Collections.Add(c);
                    }
                }

                XmlSerializer serializer = new XmlSerializer(typeof(Collection));

                using (Stream stream = File.OpenWrite(_updatePath+@"\output\packages.xml"))
                {
                    serializer.Serialize(stream, _collections);
                }
            }
        }
		/// <summary>
		/// Creates the readme files archive for the current mod.
		/// </summary>
		/// <param name="p_strArchiveFile">The archive name.</param>
		/// <param name="p_strFilesToCompress">The list of files to compress.</param>
		protected bool CreateReadMeArchive(string p_strArchiveFile, string[] p_strFilesToCompress)
		{
			try
			{
				SevenZipCompressor szcCompressor = new SevenZipCompressor();
				szcCompressor.ArchiveFormat = OutArchiveFormat.SevenZip;
				szcCompressor.CompressionLevel = CompressionLevel.Normal;
				szcCompressor.CompressFiles(Path.Combine(m_strReadMePath, p_strArchiveFile), p_strFilesToCompress);

				foreach (string File in p_strFilesToCompress)
					FileUtil.ForceDelete(File);

				return true;
			}
			catch
			{
				return false;
			}
		}
示例#17
0
            public override void Execute()
            {
                var libraryPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(GetType().Assembly.Location), Environment.Is64BitProcess ? "7z64.dll" : "7z.dll");
                SevenZipBase.SetLibraryPath(libraryPath);

                var compressor = new SevenZipCompressor {
                    ArchiveFormat = _cmdlet.Format,
                    CompressionLevel = _cmdlet.CompressionLevel,
                    CompressionMethod = _cmdlet.CompressionMethod
                };

                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;

                var activity = directoryOrFiles.Length > 1
                    ? String.Format("Compressing {0} Files to {1}", directoryOrFiles.Length, archiveFileName)
                    : String.Format("Compressing {0} to {1}", directoryOrFiles.First(), archiveFileName);

                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));
                };

                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));
                    }
                    compressor.CompressFiles(archiveFileName, 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) {
                        compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Filter, true);
                    } else {
                        compressor.CompressDirectory(directoryOrFiles[0], archiveFileName);
                    }
                }

                WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed });
                Write("Compression finished");
            }
示例#18
0
 private void ArcPostProcessor(string FilePath)
 {
     SevenZipExtractor.SetLibraryPath(@"C:\Program Files (x86)\7-Zip\7z.dll");
     var tmp = new SevenZipCompressor();
     string PostFile = AMTUtil.GetAbsPath(WorkingDir, CurrentResource.Name + AMTConfig.ResourcePostExtension);
     tmp.CompressFiles(PostFile, FilePath);
     File.Delete(FilePath);
 }
示例#19
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);
        }
示例#20
0
            public virtual void PackSevenZipNative(IAbsoluteFilePath file, IAbsoluteFilePath dest = null) {
                Contract.Requires<ArgumentNullException>(file != null);
                Contract.Requires<ArgumentException>(file.Exists);

                if (dest == null)
                    dest = (file + ".7z").ToAbsoluteFilePath();

                var compressor = new SevenZipCompressor {
                    CompressionLevel = CompressionLevel.Ultra,
                    CompressionMethod = CompressionMethod.Lzma2,
                    CompressionMode = CompressionMode.Create
                };

                var dir = dest.ParentDirectoryPath;
                dir.MakeSurePathExists();

                compressor.CompressFiles(dest.ToString(), file.ToString());
            }
示例#21
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);
     }
 }
        /// <summary>
        /// Compress files individually with .7z added on the end of the filename
        /// </summary>
        /// <param name="blShuttingDown"></param>
        private void compressFile(ref bool blShuttingDown)
        {
            SevenZip.SevenZipCompressor compressor = null;
            SevenZip.SevenZipExtractor extractor = null;
            Stream exreader = null;
            Stream creader = null;
            Stream extestreader = null;
            string[] strfilearr = new string[1];

            try
            {
                AllFiles = Common.WalkDirectory(SourceFolder, ref blShuttingDown, FileNameFilter);
                SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder());
                if (SourceFolder != DestinationFolder)
                {
                    Common.CreateDestinationFolders(SourceFolder, DestinationFolder);
                }
                if (blShuttingDown)
                {
                    throw new Exception("Shutting Down");
                }
                //Loop through every file
                foreach (System.IO.FileInfo file1 in AllFiles)
                {
                    string str7File = Common.WindowsPathClean(file1.FullName + ".7z");
                    string strDestination = Common.WindowsPathCombine(DestinationFolder, str7File, SourceFolder);

                    bool blArchiveOk = false;

                    if (blShuttingDown)
                    {
                        _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + file1.FullName, System.Diagnostics.EventLogEntryType.Information, 5130, 50);
                        throw new Exception("Shutting Down");
                    }

                    //Skip over already compressed files
                    if (file1.Extension.ToLower() == ".7z" || file1.Extension.ToLower() == ".zip" || file1.Extension.ToLower() == ".rar")
                    {
                        continue;
                    }

                    if (Common.IsFileLocked(file1))
                    {
                        _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5130, 50);
                        continue;
                    }

                    if (!startCompressing(file1.LastWriteTime))
                    {
                        continue;
                    }

                    try
                    {

                        if (File.Exists(strDestination))
                        {
                            extestreader = new FileStream(strDestination, FileMode.Open);
                            extractor = new SevenZipExtractor(extestreader);

                            //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original
                            if (extractor.Check() && KeepOriginalFile == false)
                            {

                                FileInfo file2 = new FileInfo(strDestination);
                                //Same File compressed then ok to delete
                                if (file1.LastWriteTime == file2.LastWriteTime && file1.Length == extractor.UnpackedSize && extractor.FilesCount == 1)
                                {
                                    //File.SetAttributes(file1.FullName, FileAttributes.Normal);
                                    file1.IsReadOnly = false;
                                    File.Delete(file1.FullName);
                                }
                                file2 = null;
                            }

                            continue;
                        }
                    }
                    catch (Exception)
                    {
                        _evt.WriteEntry("Compress: Failed to Delete Original File: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                        continue;

                    }
                    finally
                    {
                        if (extestreader != null)
                        {
                            extestreader.Close();
                            extestreader.Dispose();
                            extestreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                    }
                    //If file already zipped and the last modified time are the same then delete

                    //Compression of individual files
                    strfilearr[0] = file1.FullName;

                    try
                    {
                        compressor = new SevenZip.SevenZipCompressor();
                        compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
                        compressor.CompressionLevel = CompressionLvl;
                        compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {
                            compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256;

                        }

                        long lFreeSpace = 0;

                        lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder);

                        //Check for Enough Free Space to compress the file
                        if (((file1.Length * 2) > lFreeSpace) && (lFreeSpace != -1))
                        {
                            _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                            compressor = null;
                            continue;

                        }

                        if (lFreeSpace == -1)
                        {
                            _evt.WriteEntry("Compress: Only files local to this machine should be compressed.  Performance problem can occur with large files over the network. " + file1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50);
                        }

                        //Compress or Compress and Encrypt Files
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {

                            creader = new FileStream(str7File, FileMode.OpenOrCreate);

                            //Encrypt the file if password is specified
                            AES256 aes = new AES256(ep);
                            string upassword = aes.Decrypt(_encryptionPassword);
                            compressor.CompressFilesEncrypted(creader, upassword, strfilearr);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7File, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader, upassword);
                            upassword = "";
                        }
                        else
                        {
                            if (Common.IsFileLocked(file1))
                            {
                                _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5070, 50);
                                continue;
                            }
                            creader = new FileStream(str7File, FileMode.OpenOrCreate);

                            compressor.CompressFiles(creader, strfilearr);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7File, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader);

                        }

                        //7Zip file ok?
                        blArchiveOk = extractor.Check();
                        exreader.Close();
                        exreader.Dispose();
                        exreader = null;
                        verifyArchive(blArchiveOk, str7File, file1.FullName);

                    }
                    catch (Exception ex)
                    {
                        _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50);
                    }
                    finally
                    {
                        if (creader != null)
                        {
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                        }
                        if (exreader != null)
                        {
                            exreader.Close();
                            exreader.Dispose();
                            exreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                        compressor = null;
                    }

                }// end foreach
                _evt.WriteEntry("Compress: Complete Files Compressed: " + FilesCompressed.Count, System.Diagnostics.EventLogEntryType.Information, 5000, 50);
            }
            catch (Exception ex)
            {
                _evt.WriteEntry("Compress: Compress Files Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50);
            }
            finally
            {
                if (creader != null)
                {
                    creader.Close();
                    creader.Dispose();
                    creader = null;
                }
                if (exreader != null)
                {
                    exreader.Close();
                    exreader.Dispose();
                    exreader = null;
                }
                if (extractor != null)
                {
                    extractor.Dispose();
                    extractor = null;
                }
                if (extestreader != null)
                {
                    extestreader.Close();
                    extestreader.Dispose();
                    extestreader = null;
                }
                compressor = null;
            }
        }