コード例 #1
0
 public ArchiveUpdateCallback(Dictionary <Stream, string> streamDict, string password, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
     : base(password)
 {
     this.Init(streamDict, compressor, updateData, directoryStructure);
 }
コード例 #2
0
        public static List <LogInfo> Compress(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_Compress info = cmd.Info.Cast <CodeInfo_Compress>();

            #region Event Handlers
            void ReportCompressProgress(object sender, ProgressEventArgs e)
            {
                s.MainViewModel.BuildCommandProgressValue = e.PercentDone;
                s.MainViewModel.BuildCommandProgressText  = $"Compressing... ({e.PercentDone}%)";
            }

            #endregion

            // Parse arguments / parameters
            string srcPath     = StringEscaper.Preprocess(s, info.SrcPath);
            string destArchive = StringEscaper.Preprocess(s, info.DestArchive);
            SevenZip.OutArchiveFormat outFormat = ArchiveFile.ToSevenZipOutFormat(info.Format);
            SevenZip.CompressionLevel compLevel = SevenZip.CompressionLevel.Normal;
            if (info.CompressLevel is ArchiveFile.CompressLevel level)
            {
                try
                {
                    compLevel = ArchiveFile.ToSevenZipLevel(level);
                }
                catch (ArgumentException)
                { // Should have been filtered by CodeParser
                    logs.Add(new LogInfo(LogState.CriticalError, $"Invalid ArchiveHelper.CompressLevel [{info.CompressLevel}]"));
                    return(logs);
                }
            }

            // Path Security Check
            if (!StringEscaper.PathSecurityCheck(destArchive, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            // Check if a file or directory exist under name of destArchive
            bool appendMode = false;
            if (Directory.Exists(destArchive))
            {
                return(LogInfo.LogErrorMessage(logs, $"[{destArchive}] should be a file, not a directory"));
            }
            if (File.Exists(destArchive))
            {
                logs.Add(new LogInfo(LogState.Overwrite, $"Appending to archive [{destArchive}]"));
                appendMode = true;
            }

            // If parent directory of destArchive does not exist, create it
            Directory.CreateDirectory(FileHelper.GetDirNameEx(destArchive));

            // Prepare SevenZipSharp compressor
            string tempDir = FileHelper.GetTempDir();
            try
            {
                SevenZipCompressor compressor = new SevenZipCompressor(tempDir)
                {
                    ArchiveFormat    = outFormat,
                    CompressionMode  = appendMode ? CompressionMode.Append : CompressionMode.Create,
                    CompressionLevel = compLevel,
                };

                // Set filename encoding to UTF-8
                // 7z files always use Unicode filename, so no action is required.
                switch (outFormat)
                {
                case OutArchiveFormat.Zip:
                    compressor.CustomParameters["cu"] = "on";     // Force UTF-8 for filename
                    // Deflate require less memory than LZMA2 (131MB in 4T, 259MB in 8T), so let's allow multithreading here.
                    compressor.CustomParameters["mt"] = "on";     // Multithread compression
                    break;

                case OutArchiveFormat.SevenZip:
                    // TODO: Find an 7zip API which allow us query memory requirements.
                    // Threaded LZMA2 requries a lot of memory (720MB in 4T, 1376MB in 8T), and it may cause problem in low-memory environment.
                    // compressor.CustomParameters["mt"] = "on"; // Multithread compression
                    break;
                }

                string wildcard = Path.GetFileName(srcPath);
                if (!StringHelper.IsWildcard(wildcard))
                { // No wildcard
                    if (File.Exists(srcPath))
                    {
                        // Compressor Options
                        compressor.DirectoryStructure = false;

                        // Compressor Callbacks
                        compressor.Compressing += ReportCompressProgress;

                        s.MainViewModel.SetBuildCommandProgress("Compress Progress");
                        try
                        {
                            compressor.CompressFiles(destArchive, srcPath);
                        }
                        finally
                        {
                            compressor.Compressing -= ReportCompressProgress;
                            s.MainViewModel.ResetBuildCommandProgress();
                        }
                    }
                    else if (Directory.Exists(srcPath))
                    {
                        // Compressor Options
                        compressor.DirectoryStructure      = true;
                        compressor.PreserveDirectoryRoot   = true;
                        compressor.IncludeEmptyDirectories = true;

                        // Compressor Callbacks
                        compressor.Compressing += ReportCompressProgress;

                        s.MainViewModel.SetBuildCommandProgress("Compress Progress");
                        try
                        {
                            compressor.CompressDirectory(srcPath, destArchive);
                        }
                        finally
                        {
                            compressor.Compressing -= ReportCompressProgress;
                            s.MainViewModel.ResetBuildCommandProgress();
                        }
                    }
                    else
                    {
                        return(LogInfo.LogErrorMessage(logs, $"Cannot find [{srcPath}]"));
                    }

                    if (File.Exists(destArchive))
                    {
                        logs.Add(new LogInfo(LogState.Success, $"[{srcPath}] compressed to [{destArchive}]"));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Compressing to [{srcPath}] failed"));
                    }
                }
                else
                { // With wildcard
                    string   srcDirToFind = Path.GetDirectoryName(srcPath);
                    string[] files        = FileHelper.GetFilesEx(srcDirToFind, wildcard, SearchOption.AllDirectories);

                    // Compressor Options
                    compressor.DirectoryStructure      = true;
                    compressor.PreserveDirectoryRoot   = true;
                    compressor.IncludeEmptyDirectories = true;

                    // Compressor Callbacks
                    compressor.Compressing += ReportCompressProgress;

                    s.MainViewModel.SetBuildCommandProgress("Compress Progress");
                    try
                    {
                        compressor.CompressFiles(destArchive, files);
                        foreach (string f in files)
                        {
                            logs.Add(new LogInfo(LogState.Success, $"Compressed [{f}]"));
                        }
                    }
                    finally
                    {
                        compressor.Compressing -= ReportCompressProgress;
                        s.MainViewModel.ResetBuildCommandProgress();
                    }

                    if (File.Exists(destArchive))
                    {
                        logs.Add(new LogInfo(LogState.Success, $"[{files.Length}] files compressed to [{destArchive}]"));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Compressing to [{srcPath}] failed"));
                    }
                }
            }
            finally
            {
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir);
                }
            }


            return(logs);
        }
コード例 #3
0
 public ArchiveUpdateCallback(FileInfo[] files, int rootLength, string password, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
     : base(password)
 {
     this.Init(files, rootLength, compressor, updateData, directoryStructure);
 }
コード例 #4
0
        /// <summary>
        /// Write a set of input files to a torrent7z archive (assuming the same output archive name)
        /// </summary>
        /// <param name="inputFiles">Input files to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the archive was written properly, false otherwise</returns>
        public override bool Write(List <string> inputFiles, string outDir, List <Rom> roms, bool date = false, bool romba = false)
        {
            bool   success  = false;
            string tempFile = Path.Combine(outDir, "tmp" + Guid.NewGuid().ToString());

            // If either list of roms is null or empty, return
            if (inputFiles == null || roms == null || inputFiles.Count == 0 || roms.Count == 0)
            {
                return(success);
            }

            // If the number of inputs is less than the number of available roms, return
            if (inputFiles.Count < roms.Count)
            {
                return(success);
            }

            // If one of the files doesn't exist, return
            foreach (string file in inputFiles)
            {
                if (!File.Exists(file))
                {
                    return(success);
                }
            }

            // Get the output archive name from the first rebuild rom
            string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z"));

            // Set internal variables
            SevenZipBase.SetLibraryPath("7za.dll");
            SevenZipExtractor  oldZipFile;
            SevenZipCompressor zipFile;

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(archiveFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));
                }

                // If the archive doesn't exist, create it and put the single file
                if (!File.Exists(archiveFileName))
                {
                    zipFile = new SevenZipCompressor()
                    {
                        ArchiveFormat    = OutArchiveFormat.SevenZip,
                        CompressionLevel = CompressionLevel.Normal,
                    };

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), i);
                    }

                    // Sort the keys in TZIP order
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipFile.TorrentZipStringCompare);

                    // Create the temp directory
                    string tempPath = Path.Combine(outDir, Guid.NewGuid().ToString());
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }

                    // Now add all of the files in order
                    foreach (string key in keys)
                    {
                        string newkey = Path.Combine(tempPath, key);

                        File.Move(inputFiles[inputIndexMap[key]], newkey);
                        zipFile.CompressFiles(tempFile, newkey);
                        File.Move(newkey, inputFiles[inputIndexMap[key]]);

                        // After the first file, make sure we're in append mode
                        zipFile.CompressionMode = CompressionMode.Append;
                    }

                    Utilities.CleanDirectory(tempPath);
                    Utilities.TryDeleteDirectory(tempPath);
                }

                // Otherwise, sort the input files and write out in the correct order
                else
                {
                    // Open the old archive for reading
                    using (oldZipFile = new SevenZipExtractor(archiveFileName))
                    {
                        // Map all inputs to index
                        Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                        for (int i = 0; i < inputFiles.Count; i++)
                        {
                            // If the old one contains the new file, then just skip out
                            if (oldZipFile.ArchiveFileNames.Contains(roms[i].Name.Replace('\\', '/')))
                            {
                                continue;
                            }

                            inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), -(i + 1));
                        }

                        // Then add all of the old entries to it too
                        for (int i = 0; i < oldZipFile.FilesCount; i++)
                        {
                            inputIndexMap.Add(oldZipFile.ArchiveFileNames[i], i);
                        }

                        // If the number of entries is the same as the old archive, skip out
                        if (inputIndexMap.Keys.Count <= oldZipFile.FilesCount)
                        {
                            success = true;
                            return(success);
                        }

                        // Otherwise, process the old zipfile
                        zipFile = new SevenZipCompressor()
                        {
                            ArchiveFormat    = OutArchiveFormat.SevenZip,
                            CompressionLevel = CompressionLevel.Normal,
                        };

                        // Get the order for the entries with the new file
                        List <string> keys = inputIndexMap.Keys.ToList();
                        keys.Sort(ZipFile.TorrentZipStringCompare);

                        // Copy over all files to the new archive
                        foreach (string key in keys)
                        {
                            // Get the index mapped to the key
                            int index = inputIndexMap[key];

                            // If we have the input file, add it now
                            if (index < 0)
                            {
                                FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(key, inputStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                            }

                            // Otherwise, copy the file from the old archive
                            else
                            {
                                Stream oldZipFileEntryStream = new MemoryStream();
                                oldZipFile.ExtractFile(index, oldZipFileEntryStream);
                                oldZipFileEntryStream.Seek(0, SeekOrigin.Begin);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(oldZipFile.ArchiveFileNames[index], oldZipFileEntryStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                                oldZipFileEntryStream.Dispose();
                            }

                            // After the first file, make sure we're in append mode
                            zipFile.CompressionMode = CompressionMode.Append;
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }

            // If the old file exists, delete it and replace
            if (File.Exists(archiveFileName))
            {
                Utilities.TryDeleteFile(archiveFileName);
            }
            File.Move(tempFile, archiveFileName);

            // Now make the file T7Z
            // TODO: Add ACTUAL T7Z compatible code

            BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));

            bw.Seek(0, SeekOrigin.Begin);
            bw.Write(Constants.Torrent7ZipHeader);
            bw.Seek(0, SeekOrigin.End);

            using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
            {
                // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
                byte[] tempsig = Constants.Torrent7ZipSignature;
                if (oldZipFile.FilesCount > 1)
                {
                    tempsig[16] = 0x2;
                }
                else
                {
                    tempsig[16] = 0;
                }

                bw.Write(tempsig);
                bw.Flush();
                bw.Dispose();
            }

            return(true);
        }
コード例 #5
0
        public override void OnPanelVisible()
        {
            SaveFileDialog d = new SaveFileDialog
            {
                Filter   = $@"{M3L.GetString(M3L.string_7zipArchiveFile)}|*.7z",
                FileName = Utilities.SanitizePath($@"{ModForArchive.ModName}_{ModForArchive.ModVersionString}".Replace(@" ", ""), true)
            };
            var outputarchive = d.ShowDialog();

            if (outputarchive.HasValue && outputarchive.Value)
            {
                var nbw = new NamedBackgroundWorker(@"TestArchiveGenerator");
                nbw.DoWork += (a, b) =>
                {
                    var stagingPath     = Directory.CreateDirectory(Path.Combine(Utilities.GetTempPath(), @"TestGenerator")).FullName;
                    var referencedFiles = ModForArchive.GetAllRelativeReferences();
                    int numdone         = 0;
                    ActionText = M3L.GetString(M3L.string_hashingFiles);

                    Parallel.ForEach(referencedFiles, new ParallelOptions()
                    {
                        MaxDegreeOfParallelism = 3
                    }, (x) =>
                    {
                        var sourcefile = Path.Combine(ModForArchive.ModPath, x);
                        var destfile   = Path.Combine(stagingPath, x);

                        Log.Information(@"Hashing " + sourcefile);
                        var md5 = Utilities.CalculateMD5(sourcefile);
                        Directory.CreateDirectory(Directory.GetParent(destfile).FullName);
                        Log.Information(@"Writing blank hash file " + destfile);
                        File.WriteAllText(destfile, md5);


                        var done = Interlocked.Increment(ref numdone);
                        Percent  = (int)(done * 100.0 / referencedFiles.Count);
                    });
                    Log.Information(@"Copying moddesc.ini");
                    File.Copy(ModForArchive.ModDescPath, Path.Combine(stagingPath, @"moddesc.ini"), true);
                    Mod testmod = new Mod(Path.Combine(stagingPath, @"moddesc.ini"), MEGame.Unknown);
                    if (testmod.ValidMod)
                    {
                        ActionText = M3L.GetString(M3L.string_creatingArchive);

                        SevenZipCompressor svc = new SevenZipCompressor();
                        svc.Progressing += (o, details) => { Percent = (int)(details.AmountCompleted * 100.0 / details.TotalAmount); };
                        svc.CompressDirectory(stagingPath, d.FileName);
                        Utilities.HighlightInExplorer(d.FileName);
                    }
                };
                nbw.RunWorkerCompleted += (a, b) =>
                {
                    if (b.Error != null)
                    {
                        Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                    }
                    OnClosing(DataEventArgs.Empty);
                };
                nbw.RunWorkerAsync();
            }
            else
            {
                OnClosing(DataEventArgs.Empty);
            }
        }
コード例 #6
0
        /// <summary>
        /// Sets the path to the external compression library.
        /// </summary>
        /// <param name="environmentInfo">The application's envrionment info.</param>
        protected void SetCompressorPath(EnvironmentInfo environmentInfo)
        {
            var sevenZipPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll");

            SevenZipCompressor.SetLibraryPath(sevenZipPath);
        }
コード例 #7
0
        public string ExtractTempDIR(string Pathf)
        {
            int line = 0;

            try
            {
                line = 1;
                //if (!File.Exists(Application.StartupPath + "\\7z.dll"))
                //    File.WriteAllBytes(Application.StartupPath + "\\7z.dll", Properties.Resources._7z);
                line = 2;
                SevenZipCompressor.SetLibraryPath(System.Windows.Forms.Application.StartupPath + "\\7z.dll");
                line = 3;
                string fileName = Pathf;
                line = 4;
                string directory = TempDirName();
                line = 5;
                string NewFileName = TempDirName() + "\\bk1.7z";
                line = 6;
                File.Copy(fileName, NewFileName);
                line = 7;
                var extr = new SevenZipExtractor(NewFileName, _NPPWS);
                line = 8;
                //ProgressBar1.Maximum = (int)extr.FilesCount;
                line = 9;
                line = 10;
                line = 11;
                line = 12;
                extr.BeginExtractArchive(directory);
                line = 13;
                while (!_ExtractFinished)
                {
                    line = 14;
                    Thread.Sleep(100);
                    line = 15;
                    System.Windows.Forms.Application.DoEvents();
                    line = 16;
                }
                line = 17;
                foreach (var item in Directory.GetFiles(directory))
                {
                    line = 18;
                    if (item.ToUpper().EndsWith(".BAK") || item.ToUpper().EndsWith(".NP"))
                    {
                        return(item);
                    }
                    if (!item.EndsWith(".NPZ"))
                    {
                        continue;
                    }
                    File.Move(item, Path.ChangeExtension(item, ".Bak"));
                    var pathBak = item.Replace(".NPZ", ".Bak");
                    return(pathBak);
                }
                line = 19;
                return("");
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex, $"Error in Line {line}");
                return("");
            }
        }
コード例 #8
0
        private void BackupFiles(IList <IVssWMComponent> components, IDictionary <string, string> volumeMap,
                                 IDictionary <string, string> snapshotVolumeMap, IDictionary <string, string> vmNamesMap,
                                 Options options)
        {
            IList <System.IO.Stream> streams = new List <System.IO.Stream>();

            try
            {
                foreach (var component in components)
                {
                    string vmBackupPath;

                    if (options.DirectCopy)
                    {
                        vmBackupPath = Path.Combine(options.Output,
                                                    string.Format(options.OutputFormat, vmNamesMap[component.ComponentName],
                                                                  component.ComponentName,
                                                                  DateTime.Now, ""));
                    }
                    else
                    {
                        vmBackupPath = Path.Combine(options.Output,
                                                    string.Format(options.OutputFormat, vmNamesMap[component.ComponentName],
                                                                  component.ComponentName,
                                                                  DateTime.Now,
                                                                  options.ZipFormat ? ".zip" : ".7z"));
                        File.Delete(vmBackupPath);
                    }

                    var files = new Dictionary <string, System.IO.Stream>();

                    foreach (var file in component.Files)
                    {
                        string path;
                        if (file.IsRecursive)
                        {
                            path = file.Path;
                        }
                        else
                        {
                            path = Path.Combine(file.Path, file.FileSpecification);
                        }

                        // Get the longest matching path
                        var volumePath = volumeMap.Keys.OrderBy(o => o.Length).Reverse().First(o => path.StartsWith(o, StringComparison.OrdinalIgnoreCase));
                        var volumeName = volumeMap[volumePath];


                        // Exclude snapshots
                        var fileName = Path.GetFileName(path.Substring(volumePath.Length)).ToUpperInvariant();
                        var include  = !path.EndsWith("\\*");

                        var pathItems = path.Split(Path.DirectorySeparatorChar);
                        if (pathItems.Length >= 2)
                        {
                            if (pathItems[pathItems.Length - 2].ToLowerInvariant() == "snapshots")
                            {
                                include = false;
                            }
                        }

                        if (include && options.VhdInclude != null)
                        {
                            if (options.VhdInclude.Count(x => string.CompareOrdinal(x.ToUpperInvariant(), fileName) == 0) == 0)
                            {
                                include = false;
                            }
                        }

                        if (include && options.VhdIgnore != null)
                        {
                            if (options.VhdIgnore.Count(x => string.CompareOrdinal(x.ToUpperInvariant(), fileName) == 0) != 0)
                            {
                                include = false;
                            }
                        }

                        if (include)
                        {
                            if (options.DirectCopy)
                            {
                                DoDirectCopy(vmBackupPath, snapshotVolumeMap[volumeName], volumePath.Length, path);
                            }
                            else
                            {
                                AddPathToSevenZip(files, streams, snapshotVolumeMap[volumeName], volumePath.Length, path);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Ignoring file {0}", path);
                        }
                    }

                    if (!options.DirectCopy)
                    {
                        SevenZipBase.SetLibraryPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "7z.dll"));

                        var sevenZip = new SevenZipCompressor
                        {
                            ArchiveFormat         = options.ZipFormat ? OutArchiveFormat.Zip : OutArchiveFormat.SevenZip,
                            CompressionMode       = CompressionMode.Create,
                            DirectoryStructure    = true,
                            PreserveDirectoryRoot = false
                        };
                        sevenZip.CustomParameters.Add("mt", "on");


                        switch (options.CompressionLevel)
                        {
                        case 0:
                            sevenZip.CompressionLevel = CompressionLevel.None;
                            break;

                        case 1:
                            sevenZip.CompressionLevel = CompressionLevel.Fast;
                            break;

                        case 2:
                            sevenZip.CompressionLevel = CompressionLevel.Fast;
                            break;

                        case 3:
                            sevenZip.CompressionLevel = CompressionLevel.Low;
                            break;

                        case 4:
                            sevenZip.CompressionLevel = CompressionLevel.Low;
                            break;

                        case 5:
                            sevenZip.CompressionLevel = CompressionLevel.Low;
                            break;

                        case 6:
                            sevenZip.CompressionLevel = CompressionLevel.Normal;
                            break;

                        case 7:
                            sevenZip.CompressionLevel = CompressionLevel.High;
                            break;

                        case 8:
                            sevenZip.CompressionLevel = CompressionLevel.High;
                            break;

                        case 9:
                            sevenZip.CompressionLevel = CompressionLevel.Ultra;
                            break;
                        }

                        if (BackupProgress != null)
                        {
                            sevenZip.FileCompressionStarted += (sender, e) =>
                            {
                                var ebp = new BackupProgressEventArgs()
                                {
                                    AcrhiveFileName = e.FileName,
                                    Action          = EventAction.StartingArchive
                                };

                                _sevenZipCurrentFile = e.FileName;

                                Report7ZipProgress(component, volumeMap, ebp);

                                if (_cancel)
                                {
                                    e.Cancel = true;
                                }
                            };

                            sevenZip.FileCompressionFinished += (sender, e) =>
                            {
                                var ebp = new BackupProgressEventArgs
                                {
                                    AcrhiveFileName = _sevenZipCurrentFile,
                                    Action          = EventAction.ArchiveDone
                                };

                                _sevenZipCurrentFile = string.Empty;

                                Report7ZipProgress(component, volumeMap, ebp);
                            };

                            sevenZip.Compressing += (sender, e) =>
                            {
                                var ebp = new BackupProgressEventArgs
                                {
                                    AcrhiveFileName = _sevenZipCurrentFile,
                                    Action          = EventAction.PercentProgress,
                                    CurrentEntry    = _sevenZipCurrentFile,
                                    PercentDone     = e.PercentDone
                                };

                                Report7ZipProgress(component, volumeMap, ebp);

                                if (_cancel)
                                {
                                    e.Cancel = true;
                                }
                            };
                        }

                        if (string.IsNullOrEmpty(options.Password))
                        {
                            sevenZip.CompressStreamDictionary(files, vmBackupPath);
                        }
                        else
                        {
                            sevenZip.CompressStreamDictionary(files, vmBackupPath, options.Password);
                        }

                        if (_cancel)
                        {
                            if (File.Exists(vmBackupPath))
                            {
                                File.Delete(vmBackupPath);
                            }
                            throw new BackupCancelledException();
                        }
                    }
                }
            }
            finally
            {
                // Make sure that all streams are closed
                foreach (var s in streams)
                {
                    s.Close();
                }
            }
        }
コード例 #9
0
            public override void Execute()
            {
                var compressor = new SevenZipCompressor {
                    ArchiveFormat           = _cmdlet._inferredOutArchiveFormat,
                    CompressionLevel        = _cmdlet.CompressionLevel,
                    CompressionMethod       = _cmdlet.CompressionMethod,
                    VolumeSize              = _cmdlet.VolumeSize,
                    EncryptHeaders          = _cmdlet.EncryptFilenames.IsPresent,
                    DirectoryStructure      = !_cmdlet.FlattenDirectoryStructure.IsPresent,
                    IncludeEmptyDirectories = !_cmdlet.SkipEmptyDirectories.IsPresent,
                    PreserveDirectoryRoot   = _cmdlet.PreserveDirectoryRoot.IsPresent,
                    CompressionMode         = _cmdlet.Append.IsPresent ? CompressionMode.Append : CompressionMode.Create
                };

                _cmdlet.CustomInitialization?.Invoke(compressor);

                if (_cmdlet._directoryOrFilesFromPipeline == null)
                {
                    _cmdlet._directoryOrFilesFromPipeline = new List <string> {
                        _cmdlet.Path
                    };
                }

                // true -> parameter assigned
                // false -> parameter not assigned
                var outputPathIsNotEmptyOrNull = !string.IsNullOrEmpty(_cmdlet.OutputPath);
                // Final path for the archive
                var outputPath = outputPathIsNotEmptyOrNull
                    ? _cmdlet.OutputPath
                    : _cmdlet.SessionState.Path.CurrentFileSystemLocation.Path;

                // If the `OutputPath` parameter is not assigned
                // and there is an absolute or relative directory in the `ArchiveFileName`,
                // then use it instead
                var archiveDirectory = System.IO.Path.GetDirectoryName(_cmdlet.ArchiveFileName);

                if (!string.IsNullOrEmpty(archiveDirectory) && !outputPathIsNotEmptyOrNull)
                {
                    if (System.IO.Path.IsPathRooted(archiveDirectory))
                    {
                        outputPath = archiveDirectory;
                    }
                    else // If the path isn't absolute, then combine it with the path from which the script was called
                    {
                        outputPath = System.IO.Path.Combine(outputPath, archiveDirectory);
                    }
                }

                // Check whether the output path is a path to the file
                // The folder and file name cannot be the same in the same folder
                if (File.Exists(outputPath))
                {
                    throw new ArgumentException("The output path is a file, not a directory");
                }

                // If the directory doesn't exist, create it
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                var directoryOrFiles = _cmdlet._directoryOrFilesFromPipeline
                                       .Select(System.IO.Path.GetFullPath).ToArray();
                var archiveFileName = System.IO.Path.GetFullPath(System.IO.Path.Combine(outputPath, System.IO.Path.GetFileName(_cmdlet.ArchiveFileName)));

                var activity = directoryOrFiles.Length > 1
                    ? $"Compressing {directoryOrFiles.Length} Files to {archiveFileName}"
                    : $"Compressing {directoryOrFiles[0]} to {archiveFileName}";

                var currentStatus = "Compressing";

                compressor.FilesFound += (sender, args) =>
                                         Write($"{args.Value} files found for compression");
                if (!_cmdlet.NoProgress)
                {
                    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.CompressFilesEncrypted(archiveFileName, _cmdlet._password, directoryOrFiles);
                    }
                    else
                    {
                        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");
                    }
                    var recursion = !_cmdlet.DisableRecursion.IsPresent;
                    if (_cmdlet.Filter != null)
                    {
                        if (HasPassword)
                        {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet._password, _cmdlet.Filter, recursion);
                        }
                        else
                        {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, null, _cmdlet.Filter, recursion);
                        }
                    }
                    else
                    {
                        if (HasPassword)
                        {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet._password, null, recursion);
                        }
                        else
                        {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, null, null, recursion);
                        }
                    }
                }
                if (!_cmdlet.NoProgress)
                {
                    WriteProgress(new ProgressRecord(0, activity, "Finished")
                    {
                        RecordType = ProgressRecordType.Completed
                    });
                }
                Write("Compression finished");
            }
コード例 #10
0
        public static void CompressionFile(FileInfo pSrcFile, FileInfo pTarFile)
        {
            if (pTarFile.Directory.Exists == false)
            {
                Directory.CreateDirectory(pTarFile.Directory.FullName);
            }

            if (IntPtr.Size == 4)
            {
                SevenZipCompressor.SetLibraryPath(@"x86\7z.dll");
            }
            else
            {
                SevenZipCompressor.SetLibraryPath(@"x64\7z.dll");
            }

            // Set Temp Folder
            string lCompressTempFolder = Environment.GetEnvironmentVariable("TEMP");
            var    lSevenZipCompressor = new SevenZipCompressor(lCompressTempFolder);

            // Print Temp Folder
            Console.WriteLine(lSevenZipCompressor.TempFolderPath);

            // Set CompressionLevel
            lSevenZipCompressor.CompressionLevel = SevenZip.CompressionLevel.Normal;

            // Set Compress Type
            lSevenZipCompressor.ArchiveFormat = OutArchiveFormat.SevenZip;

            // Save DirectoryStructure
            lSevenZipCompressor.DirectoryStructure = true;

            // Compress blank folder
            lSevenZipCompressor.IncludeEmptyDirectories = true;

            // Use root folder
            lSevenZipCompressor.PreserveDirectoryRoot = false;

            // Encrypt Header
            lSevenZipCompressor.EncryptHeaders = false;

            // Zip Encryption Method
            lSevenZipCompressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto;

            // Fast Compression
            // No started event, only finish event
            lSevenZipCompressor.FastCompression = false;

            // start compression file
            lSevenZipCompressor.FileCompressionStarted += (sender, eventArgs) =>
            {
                BQLog.UpdateProgress("开始压缩:" + eventArgs.FileName, 0, 100);
            };

            //lSevenZipCompressor.FileCompressionFinished += (sender, eventArgs) =>
            //{
            //    BQLog.UpdateProgress("FileCompressionFinished", 100, 100);
            //};

            lSevenZipCompressor.Compressing += (sender, eventArgs) =>
            {
                BQLog.UpdateProgress("压缩中(" + eventArgs.PercentDone + "%):" + pSrcFile.Name, eventArgs.PercentDone, 100);
            };

            lSevenZipCompressor.CompressionFinished += (sender, eventArgs) =>
            {
                BQLog.UpdateProgress("压缩完成", 100, 100);
            };

            //lSevenZipCompressor.CompressFiles(pTarFile.FullName, pSrcFile.FullName + ".7z");

            Dictionary <string, string> MyDic = new Dictionary <string, string>();

            MyDic.Add(pTarFile.Name, pSrcFile.FullName);
            lSevenZipCompressor.CompressFileDictionary(MyDic, pTarFile.FullName + ".7z");
        }
コード例 #11
0
ファイル: Form_ZIP.cs プロジェクト: Dawid1989/luc-repository
        private void btnZip_Click(object sender, EventArgs e)
        {
            try
            {
                SevenZipBase.SetLibraryPath(Directory.GetCurrentDirectory() + @"\7z.dll");

                SevenZipCompressor compressor = new SevenZipCompressor();
                RndPassword        rndPass    = new RndPassword();

                int precision = rbtPrecision1.Checked ? 5 : rbtPrecision2.Checked ? 10 : rbtPrecision3.Checked ? 15 : rbtPrecision4.Checked ? 20 : 5;

                if (!string.IsNullOrWhiteSpace(tbxPathToFile.Text))
                {
                    string password           = "";
                    string sourceFiles        = tbxPathToFile.Text;
                    string zipDestinationFile = Path.GetDirectoryName(tbxPathToFile.Text) + @"\" + Path.GetFileNameWithoutExtension(tbxPathToFile.Text) + @".zip";
                    string txtDestinationFile = Path.GetDirectoryName(tbxPathToFile.Text) + @"\Password.txt";

                    if (rbtNumbers.Checked)
                    {
                        password = rndPass.Numbers(precision);
                    }
                    if (rbtLetters.Checked)
                    {
                        password = rndPass.UpperAndLower(precision);
                    }
                    if (rbtSpecial.Checked)
                    {
                        password = rndPass.SpecialCharacters(precision);
                    }
                    if (rbtRandom.Checked)
                    {
                        password = rndPass.PasswordWithManyDifferentCharacters(precision);
                    }

                    if (rbtFile.Checked == true)
                    {
                        compressor.CompressFilesEncrypted(zipDestinationFile, password, sourceFiles);
                        File.WriteAllText(txtDestinationFile, password);
                    }
                    if (rbtDictionary.Checked == true)
                    {
                        compressor.CompressDirectory(sourceFiles, zipDestinationFile, password);
                        File.WriteAllText(txtDestinationFile, password);
                    }

                    if (checkBoxClosed.Checked == true)
                    {
                        this.Close();
                    }

                    MessageBox.Show("Pik ZIP został stworzony" + Environment.NewLine + string.Format("Hasło zostało zapisane w {0}", txtDestinationFile), "ZIP z hasłem", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    tbxPathToFile.Clear();
                    defaultButton();
                }
                else
                {
                    MessageBox.Show("Brak ścieżki do pliku", "Uwaga !!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                tbxPathToFile.Clear();
                defaultButton();
            }
        }
コード例 #12
0
ファイル: DB_Form.cs プロジェクト: jlovenpk1/LOJ
            protected override bool Do()
            {
                var CurrentCount = 0;
                var MaxCount     = 101;

                try
                {
                    string savepath;
                    var    SevenPack = new SevenZipCompressor();

                    SevenPack.CompressionLevel        = CompressionLevel.Ultra;
                    SevenPack.IncludeEmptyDirectories = false;

                    SevenZip.SevenZipCompressor.SetLibraryPath(
                        Path.Combine(
                            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                            AutoUpdate.Get7zdllName()));

                    var DT = DateTime.Now;

                    var allDrives = DriveInfo.GetDrives();

                    for (int i = 0; i < allDrives.Length; i++)
                    {
                        if (allDrives[i].DriveType == DriveType.Fixed && allDrives[i].TotalFreeSpace > (10 * 1024 * 1024))
                        {
                            savepath = allDrives[i].RootDirectory.Name + "dmp\\loj";

                            if (!Directory.Exists(savepath))
                            {
                                Directory.CreateDirectory(savepath);
                            }

                            goto ItsOk;
                        }
                    }

                    Action("Нет свободного места", MaxCount, MaxCount);
                    return(false);

                    ItsOk :;

                    SevenPack.Compressing += (percentDone, percentDelta) =>
                    {
                        CurrentCount = percentDelta.PercentDone;
                        Action("Архивирование " + percentDelta.PercentDone.ToString() + " из " + 100, MaxCount, CurrentCount);
                    };

                    FileName = savepath + "\\" + data.User <string>(C.User.Login) + ' ' + data.User <string>(C.User.PCName) + ' ' + DT.Day.ToString() + "." + DT.Month.ToString() + "." + DT.Year.ToString() + ' ' + DT.Hour.ToString() + "." + DT.Minute.ToString() + "." + DT.Second.ToString() + ".7z";

                    SevenPack.CompressDirectory(Application.StartupPath, FileName);

                    Action("Отправка", MaxCount, CurrentCount++);

                    var From       = new MailAddress(data.PrgSettings.Values[(int)data.Strings.MailLogin].String, "Me");
                    var To         = new MailAddress(data.PrgSettings.Values[(int)data.Strings.MailLogin].String, "Me");
                    var NewMessage = new MailMessage(From, To);
                    NewMessage.Subject = "dmp";
                    NewMessage.Attachments.Add(new Attachment(FileName));
                    Smtp.Send(NewMessage);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                Action("Готово", MaxCount, CurrentCount++);

                return(true);
            }
コード例 #13
0
        /// <summary>
        /// 文件打包下载
        /// </summary>
        private void DownloadPackage(HttpContext Context)
        {
            SevenZipCompressor Compressor        = default(SevenZipCompressor);
            Hashtable          FileTable         = new Hashtable();
            string             PackageId         = "";
            string             PackageFolderPath = "";
            string             PackageFilePath   = "";
            int    Id          = 0;
            int    Folder      = 0;
            string FolderPath  = "";
            string CodeId      = "";
            string Name        = "";
            string Extension   = "";
            string StoragePath = "";
            string FilePath    = "";
            int    Index       = 0;

            PackageId = Guid.NewGuid().ToString();

            PackageFolderPath = Base.Common.PathCombine(Context.Server.MapPath("/storage/file/temp/"), PackageId);

            if (Directory.Exists(PackageFolderPath) == false)
            {
                Directory.CreateDirectory(PackageFolderPath);
            }

            PackageFilePath = Base.Common.PathCombine(Context.Server.MapPath("/storage/file/temp/"), "" + PackageId + ".zip");

            try
            {
                if (Context.Request.QueryString.GetValues("Id").Length == 0)
                {
                    return;
                }

                for (Index = 0; Index < Context.Request.QueryString.GetValues("Id").Length; Index++)
                {
                    if (Context.Response.IsClientConnected == false)
                    {
                        return;
                    }

                    if (Base.Common.IsNumeric(Context.Request.QueryString.GetValues("Id")[Index]) == true)
                    {
                        Id = Context.Request.QueryString.GetValues("Id")[Index].TypeInt();
                    }
                    else
                    {
                        continue;
                    }

                    Base.Data.SqlDataToTable("Select DBS_Id, DBS_Folder, DBS_FolderPath, DBS_CodeId, DBS_Name, DBS_Extension, DBS_Recycle From DBS_File Where DBS_Recycle = 0 And DBS_Id = " + Id, ref Conn, ref FileTable);

                    if (FileTable["Exist"].TypeBool() == false)
                    {
                        continue;
                    }
                    else
                    {
                        Folder     = FileTable["DBS_Folder"].TypeInt();
                        FolderPath = FileTable["DBS_FolderPath"].TypeString();
                        CodeId     = FileTable["DBS_CodeId"].TypeString();
                        Name       = FileTable["DBS_Name"].TypeString();
                        Extension  = FileTable["DBS_Extension"].TypeString();
                    }

                    FileTable.Clear();

                    if (AppCommon.PurviewCheck(Id, false, "downloader", ref Conn) == false)
                    {
                        continue;
                    }

                    StoragePath = Context.Server.MapPath("/storage/file/");

                    if (Folder == 1)
                    // 导出文件夹
                    {
                        ExportFolder(Id, StoragePath, PackageFolderPath, Context);
                    }
                    else
                    // 导出文件
                    {
                        FilePath = Base.Common.PathCombine(StoragePath, FolderPath.Substring(1), CodeId + Extension);

                        if (File.Exists(FilePath) == false)
                        {
                            continue;
                        }

                        File.WriteAllBytes(Base.Common.PathCombine(PackageFolderPath, Name + Extension), ReadFileBytes(FilePath, CodeId));

                        AppCommon.Log(Id, "file-download", ref Conn);
                    }
                }

                // 压缩文件夹
                SevenZipCompressor.SetLibraryPath(Context.Server.MapPath("/bin/7z64.dll"));

                Compressor = new SevenZipCompressor();

                Compressor.ArchiveFormat    = OutArchiveFormat.Zip;
                Compressor.CompressionLevel = CompressionLevel.High;
                Compressor.CompressDirectory(PackageFolderPath, PackageFilePath);

                Compressor = null;

                // 输出zip文件
                OutputZip(PackageFilePath, Context);
            }
            catch (Exception ex)
            {
                AppCommon.Error(ex);

                Context.Response.StatusCode = 500;
            }
            finally
            {
                if (Base.Common.IsNothing(Compressor) == false)
                {
                    Compressor = null;
                }

                Directory.Delete(PackageFolderPath, true);

                File.Delete(PackageFilePath);

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: erasmux/modorganizer-NCC
        static int DoInstall(string game, string filename, string installationPath, string profilePath, string gamePath,
                             List <string> additionalSearchPaths, string seVersion, ref string errorString)
        {
            if (game == null)
            {
                errorString = "no game specified";
                return(1);
            }
            if (filename == null)
            {
                errorString = "no file specified";
                return(1);
            }
            if (profilePath == null)
            {
                errorString = "no profile path specified";
                return(1);
            }
            if (gamePath == null)
            {
                errorString = "no game path specified";
                return(1);
            }
            try
            {
                EnvironmentInfo environmentInfo = new EnvironmentInfo(Properties.Settings.Default);

                string   exeLocation = Assembly.GetExecutingAssembly().Location;
                string   exePath     = System.IO.Path.GetDirectoryName(exeLocation);
                string[] gameModes   = Directory.GetFiles(Path.Combine(exePath, "GameModes"), String.Format("{0}.dll", game));
                if (gameModes.Count() == 0)
                {
                    errorString = "unknown game";
                    return(1);
                }

                Assembly         gameAssembly    = Assembly.LoadFrom(gameModes[0]);
                IGameModeFactory gameModeFactory = null;
                Type[]           exportedTypes   = gameAssembly.GetExportedTypes();
                foreach (Type type in exportedTypes)
                {
                    if (typeof(IGameModeFactory).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EnvironmentInfo) });
                        gameModeFactory = (IGameModeFactory)constructor.Invoke(new Object[] { environmentInfo });
                    }
                }
                if (gameModeFactory == null)
                {
                    errorString = "invalid game";
                    return(1);
                }

                string str7zPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll");
                SevenZipCompressor.SetLibraryPath(str7zPath);

                FileUtil fileUtil = new NexusFileUtil(environmentInfo);

                environmentInfo.Settings.InstallationPaths[gameModeFactory.GameModeDescriptor.ModeId] = installationPath;
                environmentInfo.Settings.ModFolder[gameModeFactory.GameModeDescriptor.ModeId]         = installationPath;
//                environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = environmentInfo.TemporaryPath;
                environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = Path.Combine(installationPath, "temp");
                if (environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] == null)
                {
                    environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] = new KeyedSettings <string>();
                }
                if (environmentInfo.Settings.DelayedSettings["ALL"] == null)
                {
                    environmentInfo.Settings.DelayedSettings["ALL"] = new KeyedSettings <string>();
                }

                ViewMessage warning = null;

                IGameMode gameMode = gameModeFactory.BuildGameMode(fileUtil, out warning);

                IModCacheManager cacheManager = new NexusModCacheManager(environmentInfo.TemporaryPath, gameMode.GameModeEnvironmentInfo.ModDirectory, fileUtil);

                IScriptTypeRegistry scriptTypeRegistry = ScriptTypeRegistry.DiscoverScriptTypes(Path.Combine(Path.GetDirectoryName(exeLocation), "ScriptTypes"), gameMode, new List <string>());
                if (scriptTypeRegistry.Types.Count == 0)
                {
                    errorString = "No script types were found.";
                    return(2);
                }

                // use a proxy so we can intercept accesses to the IGameMode interface. This allows us to make the additional search paths accessible from
                // the sandbox and feed in the script extender version even though the nmm lib won't find it.
                // This has to happen after DiscoverScriptTypes becaus that function tries to localize the assembly which fails for the dynamic assembly
                // of the proxy. Fortunately DiscoverScriptTypes has no side-effects on the gameMode.
                // This recreates the gamemode object so it's important no code above modifies gameMode
                ProxyGenerator      generator   = new ProxyGenerator();
                GameModeInterceptor interceptor = new GameModeInterceptor(additionalSearchPaths, seVersion != null ? new Version(seVersion) : null);

                gameMode = (IGameMode)generator.CreateClassProxy(gameMode.GetType(), new object[] { environmentInfo, fileUtil }, new IInterceptor[] { interceptor });

                IModFormatRegistry formatRegistry = ModFormatRegistry.DiscoverFormats(cacheManager, gameMode.SupportedFormats, scriptTypeRegistry, Path.Combine(Path.GetDirectoryName(exeLocation), "ModFormats"));
                if (formatRegistry.Formats.Count == 0)
                {
                    errorString = "No formats were found.";
                    return(2);
                }

                // we install the mod from the temporary path. Unfortunately this requires the archive to be copied, otherwise the sandbox will
                // prevent the installer script from accessing the archive in its original location
                string fileNameTemporary = Path.Combine(environmentInfo.TemporaryPath, Path.GetFileName(filename));
                File.Copy(filename, fileNameTemporary);
                IMod mod = CreateMod(fileNameTemporary, formatRegistry, gameMode);
                if (mod == null)
                {
                    errorString = "failed to initialize mod";
                    return(3);
                }

                System.IO.File.WriteAllText(installationPath + "/__installInfo.txt", mod.ModName + "\n" + mod.HumanReadableVersion + "\n" + mod.Id);

                if (mod.HasInstallScript)
                {
                    DummyDataFileUtilFactory dummyFactory = null;
                    IDataFileUtil            dataFileUtility;
                    Logger.Info("Detected C# script that relies on files in the actual data folder");

                    string modlistFile = Path.Combine(profilePath, "modlist.txt");
                    // ASSUMED mods path is the parent directory of the gameMode.InstallationPath
                    string modsPath = Directory.GetParent(gameMode.InstallationPath).FullName;
                    // Prepare dummy data directory
                    dummyFactory    = new DummyDataFileUtilFactory(gameMode.GameModeEnvironmentInfo.InstallationPath, modlistFile, modsPath, gamePath, additionalSearchPaths);
                    dataFileUtility = dummyFactory.CreateDummyDataFileUtil();

                    TxFileManager  fileManager     = new TxFileManager();
                    IInstallLog    installLog      = new DummyInstallLog();
                    IIniInstaller  iniIniInstaller = new IniInstaller(mod, installLog, fileManager, delegate { return(OverwriteResult.No); });
                    IPluginManager pluginManager   = new DummyPluginManager(Path.Combine(profilePath, "plugins.txt"), gameMode, mod);
                    IGameSpecificValueInstaller gameSpecificValueInstaller = gameMode.GetGameSpecificValueInstaller(mod, installLog, fileManager, new NexusFileUtil(environmentInfo), delegate { return(OverwriteResult.No); });
                    IModFileInstaller           fileInstaller = new ModFileInstaller(gameMode.GameModeEnvironmentInfo, mod, installLog, pluginManager, dataFileUtility, fileManager, delegate { return(OverwriteResult.No); }, false);
                    InstallerGroup       installers           = new InstallerGroup(dataFileUtility, fileInstaller, iniIniInstaller, gameSpecificValueInstaller, pluginManager);
                    IVirtualModActivator modActivator         = new DummyVirtualModActivator(gameMode, environmentInfo);
                    IScriptExecutor      executor             = mod.InstallScript.Type.CreateExecutor(mod, gameMode, environmentInfo, modActivator, installers, SynchronizationContext.Current);
                    // run the script in a second thread and start the main loop in the main thread to ensure we can handle message boxes and the like
                    ScriptRunner runner = new ScriptRunner(executor, mod.InstallScript);

                    runner.Execute();
                    runner.TaskEnded += delegate
                    {
                        iniIniInstaller.FinalizeInstall();
                        gameSpecificValueInstaller.FinalizeInstall();
                        mod.EndReadOnlyTransaction();

                        Application.Exit();
                    };

                    Application.Run();
                    switch (runner.Status)
                    {
                    case BackgroundTasks.TaskStatus.Cancelled: return(11);

                    case BackgroundTasks.TaskStatus.Error: return(6);

                    case BackgroundTasks.TaskStatus.Incomplete: return(10);

                    default: return(0);
                    }
                }
                else
                {
                    errorString = "no install script";
                    return(4);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception: " + e.Message);
                MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(5);
            }
        }
コード例 #15
0
 public FOMOD(ILog log)
 {
     Log = log;
     SevenZipCompressor.SetLibraryPath(Path.Combine(Paths.AssetsDir, Paths.SevenZipBinaries, Environment.Is64BitProcess ? Paths.SevenZipX64 : Paths.SevenZipX32));
 }
コード例 #16
0
        public void onFacadeClicked(MediaPortal.GUI.Library.Action.ActionType ButtonPressed)
        {
            ExtendedGUIListItem currentItem = (ExtendedGUIListItem)facade.SelectedListItem;

            //Show games for selected emulator
            if (currentEmulator == null && ButtonPressed != MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                if (ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_NEXT_ITEM)
                {
                    Executor.launchDocument(currentItem.AssociatedEmulator);
                }
                else
                {
                    currentEmulator = currentItem.AssociatedEmulator;
                    if (currentEmulator.isPc())
                    {
                        fillPCGames();
                    }
                    else
                    {
                        currentFolder = currentEmulator.PathToRoms;
                        fillGames();
                        facade.SelectedListItemIndex = 1;
                        onFacadeAction();
                    }
                }
            }

            //Dive into subdir
            else if (currentItem.AssociatedDirectory != null && ButtonPressed != MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                currentFolder = currentItem.AssociatedDirectory;
                fillGames();
                facade.SelectedListItemIndex = 1;
                onFacadeAction();
            }
            //Execute game
            else if (currentItem.AssociatedGame != null && ButtonPressed != MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                if (ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_NEXT_ITEM)
                {
                    Executor.launchDocument(currentItem.AssociatedGame);
                }
                else
                {
                    if (currentItem.AssociatedGame.ParentEmulator.EnableGoodmerge)
                    {
                        if (ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_MUSIC_PLAY)
                        {
                            currentItem.AssociatedGame.LaunchFile = "";
                            Executor.launchGame(currentItem.AssociatedGame);
                        }
                        else
                        {
                            if (ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_PAUSE)
                            {
                                currentItem.AssociatedGame.LaunchFile = "";
                            }

                            if (currentItem.AssociatedGame.LaunchFile.Trim() != "")
                            {
                                Executor.launchGame(currentItem.AssociatedGame);
                                fillGames();

                                for (int i = 0; i < facade.Count; i++)
                                {
                                    try
                                    {
                                        if (((ExtendedGUIListItem)facade[i]).AssociatedGame.Path == currentItem.AssociatedGame.Path)
                                        {
                                            facade.SelectedListItemIndex = i;
                                            onFacadeAction();
                                        }
                                    }
                                    catch { }
                                }
                            }
                            else
                            {
                                SevenZipCompressor.SetLibraryPath(Options.getStringOption("7zdllpath"));
                                using (SevenZipExtractor tmp = new SevenZipExtractor(currentItem.AssociatedGame.Path))
                                {
                                    string GoodmergeTempPath = "";

                                    if (currentItem.AssociatedGame.ParentEmulator.GoodmergeTempPath.EndsWith("\\"))
                                    {
                                        GoodmergeTempPath = currentItem.AssociatedGame.ParentEmulator.GoodmergeTempPath;
                                    }
                                    else
                                    {
                                        GoodmergeTempPath = currentItem.AssociatedGame.ParentEmulator.GoodmergeTempPath + "\\";
                                    }

                                    if (tmp.ArchiveFileNames.Count == 1)
                                    {
                                        Executor.launchGame(currentItem.AssociatedGame);
                                    }
                                    else
                                    {
                                        setView(0);
                                        facade.Clear();

                                        //prev selected
                                        facade.Add(ThumbsHandler.Instance.createBackDots(currentItem.AssociatedGame.Path));

                                        for (int i = 0; i < tmp.ArchiveFileNames.Count; i++)
                                        {
                                            Game RomListGame = DB.getGame(currentItem.AssociatedGame.Path, currentItem.AssociatedGame.ParentEmulator);
                                            RomListGame.LaunchFile = tmp.ArchiveFileNames[i];
                                            facade.Add(ThumbsHandler.Instance.createGameRomFacadeItem(RomListGame));

                                            Log.Error(new Exception("launch" + RomListGame.LaunchFile));
                                        }

                                        facade.SelectedListItemIndex = 1;
                                        onFacadeAction();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Executor.launchGame(currentItem.AssociatedGame);
                    }
                }
            }
            else if ((currentItem.IsBackDots || ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU) && !string.IsNullOrEmpty(currentItem.PrevSelected))
            {
                fillGames();

                for (int i = 0; i < facade.Count; i++)
                {
                    try
                    {
                        if (((ExtendedGUIListItem)facade[i]).AssociatedGame.Path == currentItem.PrevSelected)
                        {
                            facade.SelectedListItemIndex = i;
                            onFacadeAction();
                        }
                    }
                    catch { }
                }
            }
            //Go up one level
            else if ((currentItem.IsBackDots || ButtonPressed == MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU))
            {
                //Go back to all emulators
                if (currentEmulator.isManyEmulators() || currentEmulator.isPc() || currentFolder.Equals(currentEmulator.PathToRoms))
                {
                    currentEmulator     = null;
                    currentFolder       = null;
                    currentSqlTail      = null;
                    currentGameProperty = gameProperty.none;
                    fillEmulators();
                    facade.SelectedListItemIndex = 0;
                    onFacadeAction();
                }
                //Go back to parent directory
                else
                {
                    currentFolder = currentFolder.Remove(currentFolder.LastIndexOf("\\"));
                    fillGames();
                    facade.SelectedListItemIndex = 1;
                }
            }
        }
コード例 #17
0
 protected override void compressDirectory(SevenZipCompressor zip, string path, string name)
 {
     ArchiveName = name;
     DirPath     = path;
     //base.compressDirectory(zip, path, name);
 }
コード例 #18
0
            public override void Execute()
            {
                var compressor = new SevenZipCompressor {
                    ArchiveFormat = _cmdlet._inferredOutArchiveFormat,
                    CompressionLevel = _cmdlet.CompressionLevel,
                    CompressionMethod = _cmdlet.CompressionMethod,
                    VolumeSize = _cmdlet.VolumeSize,
                    EncryptHeaders = _cmdlet.EncryptFilenames.IsPresent,
                    DirectoryStructure = !_cmdlet.FlattenDirectoryStructure.IsPresent,
                    IncludeEmptyDirectories = !_cmdlet.SkipEmptyDirectories.IsPresent,
                    CompressionMode = _cmdlet.Append.IsPresent ? CompressionMode.Append : CompressionMode.Create
                };

                _cmdlet.CustomInitialization?.Invoke(compressor);

                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
                    ? $"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.CompressFilesEncrypted(archiveFileName, _cmdlet.Password, directoryOrFiles);
                    } else {
                        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");
                    }
                    var recursion = !_cmdlet.DisableRecursion.IsPresent;
                    if (_cmdlet.Filter != null) {
                        if (HasPassword) {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Password, _cmdlet.Filter, recursion);
                        } else {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Filter, recursion);
                        }
                    } else {
                        if (HasPassword) {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, recursion, _cmdlet.Password);
                        } else {
                            compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, recursion);
                        }
                    }
                }

                WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed });
                Write("Compression finished");
            }
コード例 #19
0
        public bool Start()
        {
            SevenZipCompressor cmp          = null;
            string             archFileName = "";
            int line = 0;

            try
            {
                line = 1;
                //if (!System.IO.File.Exists(Application.StartupPath + "\\7z.dll"))
                //    System.IO.File.WriteAllBytes(Application.StartupPath + "\\7z.dll", BackUpDLL.Properties.Resources._7z);
                //line = 2;
                //SevenZipCompressor.SetLibraryPath(Application.StartupPath + "\\7z.dll");
                line = 3;
                cmp  = new SevenZipCompressor();
                line = 4;
                line = 5;
                line = 6;
                cmp.CompressionFinished += new EventHandler <EventArgs>(cmp_CompressionFinished);
                line           = 7;
                line           = 10;
                cmp.VolumeSize = 0;
                line           = 11;
                string directory = _Dir;
                line         = 12;
                archFileName = _ZipName;
                line         = 13;
                if (_Files == null)
                {
                    line = 14;
                    cmp.BeginCompressDirectory(directory, archFileName, _NPPWS);
                    line = 15;
                }
                else
                {
                    line = 16;
                    cmp.BeginCompressFilesEncrypted(archFileName, _NPPWS, _Files.ToArray());
                    line = 17;
                }
                line = 18;
                while (!_Finished)
                {
                    line = 19;
                    System.Threading.Thread.Sleep(100);

                    line = 20;
                    System.Windows.Forms.Application.DoEvents();
                    line = 21;
                }
                return(true);
            }
            catch (ThreadAbortException)
            {
                cmp = null;
                if (System.IO.File.Exists(archFileName))
                {
                    try
                    {
                        System.IO.File.Delete(archFileName);
                    }
                    catch (Exception)
                    {
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex, $"Line:{line}");
                return(false);
            }
        }
コード例 #20
0
ファイル: BootsTrap.cs プロジェクト: Liklainy/ReportServer
        protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
        {
            // Perform registration that should have an application lifetime
            existingContainer
            .RegisterNamedImplementation <IDataExecutor, CommonDataExecutor>("commondataex");
            existingContainer
            .RegisterNamedImplementation <IViewExecutor, CommonViewExecutor>("commonviewex");
            existingContainer
            .RegisterNamedImplementation <IViewExecutor, TaskListViewExecutor>("tasklistviewex");
            existingContainer
            .RegisterNamedImplementation <IViewExecutor, InstanceListViewExecutor>("instancelistviewex");
            existingContainer
            .RegisterSingleton <IPostMaster, PostMasterWork>();
            existingContainer
            .RegisterSingleton <ILogic, Logic>();
            existingContainer
            .RegisterImplementation <IRTask, RTask>();

            var repository = new Repository(ConfigurationManager.AppSettings["DBConnStr"]);

            existingContainer
            .RegisterInstance <IRepository, Repository>(repository);

            // Partial bootstrapper for private named implementations registration
            IPrivateBootstrapper privboots = this as IPrivateBootstrapper;

            if (privboots != null)
            {
                privboots
                .PrivateConfigureApplicationContainer(existingContainer);
            }

            #region ConfigureMonik

            var logSender = new AzureSender(
                ConfigurationManager.AppSettings["monikendpoint"],
                "incoming");

            existingContainer
            .RegisterInstance <IClientSender, AzureSender>(logSender);

            var monikSettings = new ClientSettings()
            {
                SourceName          = "ReportServer",
                InstanceName        = ConfigurationManager.AppSettings["InstanceName"],
                AutoKeepAliveEnable = true
            };

            existingContainer
            .RegisterInstance <IClientSettings, ClientSettings>(monikSettings);

            existingContainer
            .RegisterSingleton <IClientControl, MonikInstance>();

            #endregion

            #region ConfigureMapper

            var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile(typeof(MapperProfile)));
            // Hint: add to ctor if many profileSs needed: cfg.AddProfile(typeof(AutoMapperProfile));
            existingContainer.RegisterSingleInstance <MapperConfiguration, MapperConfiguration>(mapperConfig);
            var mapper = existingContainer.Resolve <MapperConfiguration>().CreateMapper();
            existingContainer.RegisterSingleInstance <IMapper, IMapper>(mapper);

            #endregion

            #region ConfigureCompressor

            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                    Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
            SevenZipBase.SetLibraryPath(path);
            var compressor = new SevenZipCompressor
            {
                CompressionMode = CompressionMode.Create,
                ArchiveFormat   = OutArchiveFormat.SevenZip
            };
            var archiver = new Archiver7Zip(compressor);
            existingContainer.RegisterSingleInstance <IArchiver, Archiver7Zip>(archiver);

            #endregion

            #region ConfigureBot

            Uri          proxyUri    = new Uri(ConfigurationManager.AppSettings["proxyUriAddr"]);
            ICredentials credentials = new NetworkCredential(ConfigurationManager.AppSettings["proxyLogin"],
                                                             ConfigurationManager.AppSettings["proxyPassword"]);
            WebProxy          proxy = new WebProxy(proxyUri, true, null, credentials);
            TelegramBotClient bot   = new TelegramBotClient(ConfigurationManager.AppSettings["BotToken"], proxy);
            existingContainer
            .RegisterSingleInstance <ITelegramBotClient, TelegramBotClient>(bot);

            #endregion

            existingContainer //why?
            .RegisterInstance <ILifetimeScope, ILifetimeScope>(existingContainer);
        }
コード例 #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="folder">Folder</param>
        /// <param name="archiveDest">Archive name</param>
        /// <param name="cplLvl">Level of compression</param>
        /// <returns></returns>
        public static bool CompressFolder(string folder, string archiveDest, int cplLvl)
        {
            if (!Directory.Exists(folder))
            {
                return(false);
            }

            _ArchiveName = archiveDest + ".7z";
            //string sSeventZipLink = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "x86", "7z.dll");
            string sSeventZipLink = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");

            //var sevenZipPath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
            if (!File.Exists(sSeventZipLink))
            {
                MessageBox.Show("7z.dll missing", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }


            SevenZipCompressor.SetLibraryPath(sSeventZipLink);
            //  var k = SevenZipCompressor.CurrentLibraryFeatures;


            SevenZipCompressor szp = new SevenZipCompressor();


            szp.CompressionLevel   = CompressionLevel.Ultra;
            szp.CompressionMode    = CompressionMode.Create;
            szp.ArchiveFormat      = OutArchiveFormat.SevenZip;
            szp.DirectoryStructure = true;

            try
            {
                szp.FilesFound  += FilesFound;
                szp.Compressing += Compressing;


                szp.FileCompressionStarted  += FileCompressionStarted;
                szp.FileCompressionFinished += FileCompressionFinished;
                szp.CompressionFinished     += CompressionFinished;


                BoxProgress      = new ProgressCompFolder();
                BoxProgress.Text = "Compression 7z";



                Task t = Task.Run(() =>
                {
                    szp.CompressDirectory(folder, _ArchiveName);
                }
                                  );

                BoxProgress.ShowDialog();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(true);
        }
コード例 #22
0
ファイル: Lzma.cs プロジェクト: metabolize-forks/smithers
        static Lzma()
        {
            string libraryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Externals\\7z.dll");

            SevenZipCompressor.SetLibraryPath(libraryPath);
        }
コード例 #23
0
        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 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()),
                                                                      _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 (Exception ex)
            {
                var dialog = new TaskDialog();
                dialog.StandardButtons = TaskDialogStandardButtons.Ok;
                dialog.Text            = ex.Message;
                dialog.Show();
            }
        }
コード例 #24
0
ファイル: Lzma.cs プロジェクト: metabolize-forks/smithers
        public static void Compress(string directory, string file)
        {
            var compressor = new SevenZipCompressor();

            compressor.CompressDirectory(directory, file);
        }
コード例 #25
0
        /// <summary>
        /// Sets the path to the external compression library.
        /// </summary>
        /// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param>
        protected void SetCompressorPath(EnvironmentInfo p_eifEnvironmentInfo)
        {
            string str7zPath = Path.Combine(p_eifEnvironmentInfo.ProgrammeInfoDirectory, p_eifEnvironmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll");

            SevenZipCompressor.SetLibraryPath(str7zPath);
        }
コード例 #26
0
        /// <summary>
        /// Download all the contents (quizzes, videos, lecture notes, ...) of the course to the given destination directory (defaults to .)
        /// </summary>
        /// <param name="courseName"> </param>
        /// <param name="destDir"></param>
        /// <param name="reverse"></param>
        /// <param name="gzipCourses"></param>
        /// <param name="weeklyTopics"> </param>
        public virtual void DownloadCourse(string courseName, string destDir, bool reverse, bool gzipCourses, Course weeklyTopics)
        {
            if (!weeklyTopics.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)
            {
                weeklyTopics.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(_courseraCourse.HOME_URL, courseName), courseDir, "index.html");
            Download(string.Format(_courseraCourse.LectureUrlFromName(courseName)), courseDir, "lectures.html");

            try
            {
                DownloadAbout(courseName, courseDir, _courseraCourse.ABOUT_URL);
            }
            catch (Exception e)
            {
                Console.WriteLine("Warning: failed to download about file: {0}", e.Message);
            }

            //now download the actual content (video's, lecture notes, ...)
            foreach (Week week in weeklyTopics.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
                 */

                // 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.ClassNum.ToString().PadLeft(2, '0') + " - " + classSegment.ClassName;

                    //ensure the class dir exists
                    string clsdir = Path.Combine(wkdir, clsdirname);
                    clsdir = Utilities.TrimPathPart(clsdir, _courseraCourse.Max_path_part_len - 15);
                    Directory.CreateDirectory(clsdir);

                    Console.WriteLine(" - Downloading resources for " + classSegment.ClassName);

                    //download each resource
                    foreach (KeyValuePair <string, string> resourceLink in classSegment.ResourceLinks)
                    {
                        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");
            }

            /*
             *
             * if gzip_courses:
             * tar_file_name = courseName + ".tar.gz"
             * print_("Compressing and storing as " + tar_file_name)
             * tar = tarfile.open(os.path.join(dest_dir, tar_file_name), 'w:gz')
             * tar.add(os.path.join(dest_dir, courseName), arcname=courseName)
             * tar.close()
             * print_("Compression complete. Cleaning up.")
             * shutil.rmtree(os.path.join(dest_dir, courseName))
             */
        }
コード例 #27
0
        /// <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)
        {
            filepath = path;
            ModName  = Path.GetFileNameWithoutExtension(path);

            FomodFile = new Archive(path);
            CachePath = Path.Combine(Program.GameMode.ModInfoCacheDirectory, ModName + ".zip");
            if (p_booUseCache && File.Exists(CachePath))
            {
                m_arcCacheFile = new Archive(CachePath);
            }

            FindPathPrefix();
            FomodFile.FilesChanged += 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(baseName) != null);

            //check for script
            foreach (var name in FomodScript.ScriptNames)
            {
                if (ContainsFile("fomod/" + name))
                {
                    m_strScriptPath = "fomod/" + name;
                    break;
                }
            }

            //check for readme
            foreach (var ext in Readme.ValidExtensions)
            {
                if (ContainsFile("readme - " + baseName + ext))
                {
                    m_strReadmePath = "Readme - " + Path.GetFileNameWithoutExtension(path) + ext;
                    break;
                }
            }
            if (String.IsNullOrEmpty(m_strReadmePath))
            {
                foreach (var ext in Readme.ValidExtensions)
                {
                    if (ContainsFile("docs/readme - " + baseName + ext))
                    {
                        m_strReadmePath = "docs/Readme - " + Path.GetFileNameWithoutExtension(path) + ext;
                        break;
                    }
                }
            }

            //check for screenshot
            var extensions = new[]
            {
                ".png", ".jpg", ".bmp"
            };

            foreach (var ext in extensions)
            {
                if (ContainsFile("fomod/screenshot" + ext))
                {
                    m_strScreenshotPath = "fomod/screenshot" + ext;
                    break;
                }
            }

            if (p_booUseCache && !File.Exists(CachePath) && (FomodFile.IsSolid || FomodFile.ReadOnly))
            {
                var 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));
                    }

                    var strFilesToCompress = Directory.GetFiles(strTmpInfo, "*.*", SearchOption.AllDirectories);
                    if (strFilesToCompress.Length > 0)
                    {
                        var szcCompressor = new SevenZipCompressor();
                        szcCompressor.ArchiveFormat    = OutArchiveFormat.Zip;
                        szcCompressor.CompressionLevel = CompressionLevel.Ultra;
                        szcCompressor.CompressDirectory(strTmpInfo, CachePath);
                    }
                }
                finally
                {
                    FileUtil.ForceDelete(strTmpInfo);
                }
                if (File.Exists(CachePath))
                {
                    m_arcCacheFile = new Archive(CachePath);
                }
            }

            LoadInfo();
        }
コード例 #28
0
        /// <summary>
        /// The method that is called to start the backgound task.
        /// </summary>
        /// <param name="p_objArgs">Arguments to for the task execution.</param>
        /// <returns>Always <c>null</c>.</returns>
        protected override object DoWork(object[] p_objArgs)
        {
            OverallMessage          = "Backuping Nexus Mod Manager...";
            OverallProgress         = 0;
            OverallProgressStepSize = 1;
            ShowItemProgress        = true;
            OverallProgressMaximum  = 7;
            ItemProgressStepSize    = 1;
            FileCounter             = 0;

            OverallMessage = "Creating the directories.";
            StepOverallProgress();

            System.IO.DriveInfo drive = new System.IO.DriveInfo(EnvironmentInfo.TemporaryPath);
            drive = new System.IO.DriveInfo(drive.Name);

            long TotalFileSize = BackupManager.InstalledModFileSize + BackupManager.BaseGameFilesSize + BackupManager.LooseFilesSize + BackupManager.ModArchivesSize;

            if (drive.AvailableFreeSpace > (TotalFileSize))
            {
                string BackupDirectory = Path.Combine(EnvironmentInfo.TemporaryPath, "NMMBACKUP");
                if (Directory.Exists(BackupDirectory))
                {
                    FileUtil.ForceDelete(BackupDirectory);
                }

                Directory.CreateDirectory(BackupDirectory);
                Directory.CreateDirectory(Path.Combine(BackupDirectory, Path.GetFileName(ModManager.GameMode.PluginDirectory)));
                Directory.CreateDirectory(Path.Combine(BackupDirectory, "VIRTUAL INSTALL"));
                Directory.CreateDirectory(Path.Combine(BackupDirectory, "PROFILE"));

                bool PathLimit = CheckPathLimit(BackupDirectory);
                if (PathLimit)
                {
                    string NewBackupDirectory = Path.Combine(Directory.GetDirectoryRoot(BackupDirectory), "NMMTemp");
                    string WarningMessage     = "Warning: NMM won't be able to use the default 'temp' folder for this operation, this will cause some file paths to reach the OS limit of 260 characters and prevent files to be copied." + Environment.NewLine + Environment.NewLine;
                    WarningMessage = WarningMessage + "Just for this backup NMM will use a " + NewBackupDirectory + " folder. This folder will be removed after the backup completes.";

                    MessageBox.Show(WarningMessage, "Create Backup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    BackupDirectory = NewBackupDirectory;
                }

                int    i   = 1;
                string dir = string.Empty;

                OverallProgressMaximum = BackupManager.lstBaseGameFiles.Count();
                if ((BackupManager.checkList.Contains(0)) && (BackupManager.lstBaseGameFiles.Count > 0))
                {
                    i = 1;
                    foreach (BackupInfo bkInfo in BackupManager.lstBaseGameFiles)
                    {
                        if (i < BackupManager.lstBaseGameFiles.Count())
                        {
                            ItemMessage = bkInfo.VirtualModPath;
                            StepItemProgress();
                        }

                        OverallMessage = string.Format("Copying GAME BASE files...{0}/{1}", i++, BackupManager.lstBaseGameFiles.Count());
                        StepOverallProgress();
                        dir = Path.GetDirectoryName(Path.Combine(bkInfo.ModID, bkInfo.VirtualModPath));
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(Path.Combine(BackupDirectory, bkInfo.Directory, dir));
                        }

                        File.Copy(bkInfo.RealModPath, Path.Combine(BackupDirectory, bkInfo.Directory, bkInfo.VirtualModPath), true);
                    }

                    TotalFiles += BackupManager.lstBaseGameFiles.Count;
                }

                if ((BackupManager.checkList.Contains(1)) && (BackupManager.lstInstalledModFiles.Count > 0))
                {
                    OverallProgressMaximum = BackupManager.lstInstalledModFiles.Count();
                    foreach (BackupInfo bkInfo in BackupManager.lstInstalledModFiles)
                    {
                        OverallMessage = string.Format("Copying MODS INSTALLATION files...{0}/{1}", i++, BackupManager.lstInstalledModFiles.Count());
                        StepOverallProgress();
                        dir = Path.GetDirectoryName(Path.Combine(bkInfo.ModID, bkInfo.VirtualModPath));
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(Path.Combine(BackupDirectory, bkInfo.Directory, dir));
                        }

                        File.Copy(bkInfo.RealModPath, Path.Combine(BackupDirectory, bkInfo.Directory, bkInfo.ModID, bkInfo.VirtualModPath), true);

                        if (ItemProgress < ItemProgressMaximum)
                        {
                            ItemMessage = bkInfo.RealModPath;
                            StepItemProgress();
                        }
                    }

                    OverallProgressMaximum = BackupManager.lstInstalledNMMLINKFiles.Count();
                    foreach (BackupInfo bkInfo in BackupManager.lstInstalledNMMLINKFiles)
                    {
                        OverallMessage = string.Format("Copying NMMLINK files...{0}/{1}", i++, BackupManager.lstInstalledNMMLINKFiles.Count());
                        StepOverallProgress();
                        dir = Path.GetDirectoryName(Path.Combine("NMMLINK", bkInfo.VirtualModPath));
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(Path.Combine(BackupDirectory, dir));
                        }

                        File.Copy(bkInfo.RealModPath, Path.Combine(BackupDirectory, bkInfo.Directory, bkInfo.ModID, bkInfo.VirtualModPath), true);

                        if (ItemProgress < ItemProgressMaximum)
                        {
                            ItemMessage = bkInfo.RealModPath;
                            StepItemProgress();
                        }
                    }

                    TotalFiles += BackupManager.lstInstalledModFiles.Count + BackupManager.lstInstalledNMMLINKFiles.Count;
                }

                OverallProgressMaximum = BackupManager.lstLooseFiles.Count();
                if ((BackupManager.checkList.Contains(2)) && (BackupManager.lstLooseFiles.Count > 0))
                {
                    i = 1;
                    foreach (BackupInfo bkInfo in BackupManager.lstLooseFiles)
                    {
                        if (i < BackupManager.lstLooseFiles.Count())
                        {
                            ItemMessage = bkInfo.VirtualModPath;
                            StepItemProgress();
                        }

                        OverallMessage = string.Format("Copying " + Path.GetFileName(ModManager.GameMode.PluginDirectory) + " files...{0}/{1}", i++, BackupManager.lstLooseFiles.Count());
                        StepOverallProgress();
                        dir = Path.GetDirectoryName(Path.Combine(bkInfo.ModID, bkInfo.VirtualModPath));
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(Path.Combine(BackupDirectory, bkInfo.Directory, dir));
                        }

                        File.Copy(bkInfo.RealModPath, Path.Combine(BackupDirectory, bkInfo.Directory, bkInfo.VirtualModPath), true);
                    }

                    TotalFiles += BackupManager.lstLooseFiles.Count;
                }

                OverallProgressMaximum = BackupManager.lstModArchives.Count();
                if ((BackupManager.checkList.Contains(3)) && (BackupManager.lstModArchives.Count > 0))
                {
                    i = 1;
                    foreach (BackupInfo bkInfo in BackupManager.lstModArchives)
                    {
                        if (i < BackupManager.lstModArchives.Count())
                        {
                            ItemMessage = bkInfo.VirtualModPath;
                            StepItemProgress();
                        }

                        OverallMessage = string.Format("Copying MOD ARCHIVES...{0}/{1}", i++, BackupManager.lstModArchives.Count());
                        StepOverallProgress();
                        dir = Path.GetDirectoryName(Path.Combine(bkInfo.Directory, bkInfo.VirtualModPath));
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(Path.Combine(BackupDirectory, dir));
                        }

                        File.Copy(bkInfo.RealModPath, Path.Combine(BackupDirectory, bkInfo.Directory, bkInfo.VirtualModPath), true);
                    }

                    TotalFiles += BackupManager.lstModArchives.Count;
                }

                byte[] bteLoadOrder = null;
                if (ModManager.GameMode.UsesPlugins)
                {
                    bteLoadOrder = PluginManagerVM.ExportLoadOrder();
                }

                string[] strOptionalFiles = null;

                if (ModManager.GameMode.RequiresOptionalFilesCheckOnProfileSwitch)
                {
                    if ((PluginManager != null) && ((PluginManager.ActivePlugins != null) && (PluginManager.ActivePlugins.Count > 0)))
                    {
                        strOptionalFiles = ModManager.GameMode.GetOptionalFilesList(PluginManager.ActivePlugins.Select(x => x.Filename).ToArray());
                    }
                }

                IModProfile mprModProfile = AddProfile(null, null, bteLoadOrder, ModManager.GameMode.ModeId, -1, strOptionalFiles, Path.Combine(BackupDirectory, "PROFILE"));

                Directory.CreateDirectory(Path.Combine(BackupDirectory, ModManager.GameMode.Name));

                string installLog = Path.Combine(ModManager.GameMode.GameModeEnvironmentInfo.InstallInfoDirectory, "InstallLog.xml");

                if (File.Exists(installLog))
                {
                    File.Copy(installLog, Path.Combine(BackupDirectory, "InstallLog.xml"));
                }

                string startPath = BackupDirectory;
                string zipPath   = Path.Combine(EnvironmentInfo.ApplicationPersonalDataFolderPath, "NMM_BACKUP.zip");

                if (File.Exists(zipPath))
                {
                    File.Delete(zipPath);
                }

                OverallMessage = "Zipping the Archive...";
                StepOverallProgress();

                string strDateTimeStamp = DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern);
                strDateTimeStamp = strDateTimeStamp.Replace(":", "");
                strDateTimeStamp = strDateTimeStamp.Replace("-", "");
                strDateTimeStamp = strDateTimeStamp.Replace("T", "-");

                SevenZipCompressor szcCompressor = new SevenZipCompressor(startPath);
                szcCompressor.CompressionLevel        = SevenZip.CompressionLevel.Normal;
                szcCompressor.ArchiveFormat           = OutArchiveFormat.Zip;
                szcCompressor.FastCompression         = false;
                szcCompressor.CompressionMethod       = CompressionMethod.Default;
                szcCompressor.CompressionMode         = SevenZip.CompressionMode.Create;
                szcCompressor.FileCompressionStarted += new EventHandler <FileNameEventArgs>(compressor_FileCompressionStarted);

                szcCompressor.CompressDirectory(startPath, Path.Combine(SelectedPath, ModManager.GameMode.ModeId + "_NMM_BACKUP_" + strDateTimeStamp + ".zip"), true);

                OverallMessage = "Deleting the leftovers.";
                StepOverallProgress();
                FileUtil.ForceDelete(BackupDirectory);
            }

            return(null);
        }
コード例 #29
0
 public ArchiveUpdateCallback(Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
 {
     this.Init(stream, compressor, updateData, directoryStructure);
 }
コード例 #30
0
 protected override void compressFiles(SevenZipCompressor zip, string name, params string[] input)
 {
     ArchiveName = name;
     FilesInput  = input;
     //base.compressFiles(zip, name, input);
 }
コード例 #31
0
ファイル: 7z.cs プロジェクト: aa2g/AA2Install
        private static void SyncCompress(string filename, string workingdir, string directory)
        {
            SevenZipCompressor z = new SevenZipCompressor(filename);

            z.ProgressUpdated += (i) =>
            {
                var invoke = ProgressUpdated;
                if (invoke != null)
                {
                    invoke(i);
                }
            };

            z.CompressDirectory(directory, workingdir);
        }
コード例 #32
0
 /// <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);
 }