Exemplo n.º 1
0
        private async Task <IEnumerable <string> > LoadSetList()
        {
            var setsArchiveFilePath = Path.Combine(this.workingDirectory, AllSetsArchiveFileName);
            //var setsSubfolderPath = Path.Combine(this.workingDirectory, SetsFolderName);
            var extractionOptions = new ExtractionOptions()
            {
                ExtractFullPath = true,
                Overwrite       = true
            };

            using (var stream = File.OpenRead(setsArchiveFilePath))
            {
                using var reader = ReaderFactory.Open(stream);
                while (reader.MoveToNextEntry())
                {
                    reader.WriteEntryToDirectory(this.workingDirectory, extractionOptions);
                }
            }

            string setsText = await FileUtility.ReadAllTextAsync(SetListFileName);

            JArray parsedSetData = Utility.ParseMtGJson <JArray>(setsText);

            var setList = new List <JsonSet>();

            foreach (var set in parsedSetData)
            {
                setList.Add(set.ToObject <JsonSet>());
            }

            setList.Sort(new JsonSetComparer());

            return(setList.Select(s => s.Code));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Decompresses this file into a specified directory.
        /// </summary>
        /// <param name="destination">Desired decompression desination path.</param>
        public static void Decompress(this FileInfo @this, DirectoryInfo destination,
                                      bool extractFullPath = true, bool overwrite = false)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if ([email protected]())
            {
                throw new IOException("File does not exist: " + @this.FullName);
            }

            if (destination.Exists() && !overwrite)
            {
                throw new Exception("Destination file already exists: " + destination.FullName);
            }

            var options = new ExtractionOptions
            {
                ExtractFullPath = extractFullPath,
                Overwrite       = overwrite
            };

            using (var stream = File.OpenRead(@this.FullName))
                using (var reader = ReaderFactory.Open(stream))
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            reader.WriteEntryToDirectory(destination.FullName, options);
                        }
                    }
        }
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
        public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
                                            ExtractionOptions options = null)
        {
            string destinationFileName;
            string file = Path.GetFileName(entry.Key);

            options = options ?? new ExtractionOptions()
            {
                Overwrite = true
            };


            if (options.ExtractFullPath)
            {
                string folder  = Path.GetDirectoryName(entry.Key);
                string destdir = Path.Combine(destinationDirectory, folder);
                if (!Directory.Exists(destdir))
                {
                    Directory.CreateDirectory(destdir);
                }
                destinationFileName = Path.Combine(destdir, file);
            }
            else
            {
                destinationFileName = Path.Combine(destinationDirectory, file);
            }
            if (!entry.IsDirectory)
            {
                entry.WriteToFile(destinationFileName, options);
            }
        }
Exemplo n.º 4
0
        protected override void OnInstallPackageFiles(PV version, string packageDirectory)
        {
            var tsPackage        = ThunderstoreAPI.LookupPackage(version.group.DependencyId).First();
            var tsPackageVersion = tsPackage.versions.First(tspv => tspv.version_number.Equals(version.version));
            var filePath         = Path.Combine(packageDirectory, $"{tsPackageVersion.full_name}.zip");

            using (var client = new WebClient())
            {
                client.DownloadFile(tsPackageVersion.download_url, filePath);
            }

            using (var archive = ArchiveFactory.Open(filePath))
            {
                foreach (var entry in archive.Entries.Where(entry => entry.IsDirectory))
                {
                    var path = Path.Combine(packageDirectory, entry.Key);
                    Directory.CreateDirectory(path);
                }

                var extractOptions = new ExtractionOptions {
                    ExtractFullPath = true, Overwrite = true
                };
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    entry.WriteToDirectory(packageDirectory, extractOptions);
                }
            }

            File.Delete(filePath);
        }
Exemplo n.º 5
0
        private static void ExtractArchives(string tempFolder)
        {
            var options = new ExtractionOptions {
                ExtractFullPath = true, Overwrite = true
            };

            foreach (var fileName in Directory.GetFiles(tempFolder))
            {
                Console.WriteLine("\t" + Path.GetFileName(fileName));

                var extractedFolderName = Path.GetFileNameWithoutExtension(fileName).Replace(".tar", "");
                var exractedFolderPath  = Path.Combine(tempFolder, extractedFolderName);

                using (var fileStream = File.OpenRead(fileName))
                    using (var archive = OpenArchive(fileStream))
                    {
                        var selectedEntries = archive.Entries.Where(
                            e => e.Key.StartsWith(@"./shared/Microsoft.NETCore.App/") ||
                            e.Key.StartsWith(@"shared/Microsoft.NETCore.App/") ||
                            e.Key.StartsWith(@"shared\Microsoft.NETCore.App\"));
                        if (!selectedEntries.Any())
                        {
                            throw new InvalidDataException($"No archive selected to be extracted from {fileName} at {tempFolder}");
                        }

                        foreach (var entry in selectedEntries)
                        {
                            entry.WriteToDirectory(exractedFolderPath, options);
                        }
                    }

                File.Delete(fileName);
            }
        }
Exemplo n.º 6
0
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
        public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
                                            ExtractionOptions options = null)
        {
            string destinationFileName;
            string file = Path.GetFileName(entry.Key);

            //Console.WriteLine(file);
            //中文路径乱码转码
            //file = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(file));

            options = options ?? new ExtractionOptions()
            {
                Overwrite = true
            };


            if (options.ExtractFullPath)
            {
                string folder  = Path.GetDirectoryName(entry.Key);
                string destdir = Path.Combine(destinationDirectory, folder);
                if (!Directory.Exists(destdir))
                {
                    Directory.CreateDirectory(destdir);
                }
                destinationFileName = Path.Combine(destdir, file);
            }
            else
            {
                destinationFileName = Path.Combine(destinationDirectory, file);
            }
            if (!entry.IsDirectory)
            {
                entry.WriteToFile(destinationFileName, options);
            }
        }
Exemplo n.º 7
0
        public void UnpackInternal(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder,
                                   bool overwrite      = false, bool fullPath = true, bool checkFileIntegrity = true,
                                   ITProgress progress = null)
        {
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile));
            }
            if (outputFolder == null)
            {
                throw new ArgumentNullException(nameof(outputFolder));
            }

            var ext     = sourceFile.FileExtension;
            var options = new ExtractionOptions {
                PreserveFileTime = true
            };

            if (fullPath)
            {
                options.ExtractFullPath = true;
            }
            if (overwrite)
            {
                options.Overwrite = true;
            }
            using (var archive = GetArchiveWithGzWorkaround(sourceFile, ext))
                UnpackArchive(outputFolder, overwrite, archive, options, sourceFile);
        }
Exemplo n.º 8
0
        private void UnpackArchive(IAbsoluteDirectoryPath outputFolder, bool overwrite, IArchive archive,
                                   ExtractionOptions options, IAbsoluteFilePath sourceFile)
        {
            foreach (var p in archive.Entries.Where(entry => entry.IsDirectory)
                     .Select(entry => outputFolder.GetChildDirectoryWithName(entry.Key)))
            {
                p.MakeSurePathExists();
            }

            foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
            {
                var fileName        = entry.Key ?? sourceFile.FileNameWithoutExtension;
                var destinationFile = outputFolder.GetChildFileWithName(fileName);
                if (overwrite)
                {
                    destinationFile.MakeSureParentPathExists();
                    entry.WriteToFile(destinationFile.ToString(), options);
                }
                else
                {
                    if (destinationFile.Exists)
                    {
                        continue;
                    }
                    destinationFile.MakeSureParentPathExists();
                    entry.WriteToFile(destinationFile.ToString(), options);
                }
            }
        }
        internal static Task ExtractFile(string zipPath, string outPath, bool overwrite)
        {
            return(Task.Run(() =>
            {
                var extractOptions = new ExtractionOptions()
                {
                    ExtractFullPath = true, Overwrite = true
                };

                using (var stream = File.OpenRead(zipPath))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (reader.Entry.IsDirectory)
                        {
                            continue;
                        }

                        // NOTE: Forward slashes are allowed on Windows and required on Unixes,
                        // so just always use them here instead of trying to adapt.
                        var filePath = Path.GetFullPath(Path.Combine(outPath, reader.Entry.Key)).Replace('\\', '/');

                        var dir = Path.GetDirectoryName(filePath);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        reader.WriteEntryToFile(filePath, extractOptions);
                    }
                }
            }));
        }
        public void ApplyDeltaPackageToWorkingDirectory(string workingPath, ReleasePackage deltaPackage)
        {
            Contract.Requires(deltaPackage != null);

            string deltaPath;

            var opts = new ExtractionOptions()
            {
                ExtractFullPath = true, Overwrite = true, PreserveFileTime = true
            };

            using (Utility.WithTempDirectory(out deltaPath, localAppDirectory))
            {
                using (var za = ZipArchive.Open(deltaPackage.InputPackageFile))
                    using (var reader = za.ExtractAllEntries())
                    {
                        reader.WriteAllToDirectory(deltaPath, opts);

                        var pathsVisited = new List <string>();

                        var deltaPathRelativePaths = new DirectoryInfo(deltaPath).GetAllFilesRecursively()
                                                     .Select(x => x.FullName.Replace(deltaPath + Path.DirectorySeparatorChar, ""))
                                                     .ToArray();

                        // Apply all of the .diff files
                        deltaPathRelativePaths
                        .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                        .Where(x => !x.EndsWith(".shasum", StringComparison.InvariantCultureIgnoreCase))
                        .Where(x => !x.EndsWith(".diff", StringComparison.InvariantCultureIgnoreCase) ||
                               !deltaPathRelativePaths.Contains(x.Replace(".diff", ".bsdiff")))
                        .ForEach(file =>
                        {
                            pathsVisited.Add(Regex.Replace(file, @"\.(bs)?diff$", "").ToLowerInvariant());
                            applyDiffToFile(deltaPath, file, workingPath);
                        });

                        // Delete all of the files that were in the old package but
                        // not in the new one.
                        new DirectoryInfo(workingPath).GetAllFilesRecursively()
                        .Select(x => x.FullName.Replace(workingPath + Path.DirectorySeparatorChar, "").ToLowerInvariant())
                        .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase) && !pathsVisited.Contains(x))
                        .ForEach(x =>
                        {
                            this.Log().Info("{0} was in old package but not in new one, deleting", x);
                            File.Delete(Path.Combine(workingPath, x));
                        });

                        // Update all the files that aren't in 'lib' with the delta
                        // package's versions (i.e. the nuspec file, etc etc).
                        deltaPathRelativePaths
                        .Where(x => !x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                        .ForEach(x =>
                        {
                            this.Log().Info("Updating metadata file: {0}", x);
                            File.Copy(Path.Combine(deltaPath, x), Path.Combine(workingPath, x), true);
                        });
                    }
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Extract to specific directory, retaining filename
 /// </summary>
 public static void WriteToDirectory(this IArchive archive, string destinationDirectory,
                                     ExtractionOptions options = null)
 {
     foreach (IArchiveEntry entry in archive.Entries.Where(x => !x.IsDirectory))
     {
         entry.WriteToDirectory(destinationDirectory, options);
     }
 }
        /// <inheritdoc/>
        public override async Task <IList <CompressedEntryModel> > ExtractAsync(string sourcePath, string destinationPath, CancellationToken ct)
        {
            if (string.IsNullOrWhiteSpace(sourcePath))
            {
                throw new ArgumentNullException(nameof(sourcePath));
            }

            if (string.IsNullOrWhiteSpace(destinationPath))
            {
                throw new ArgumentNullException(nameof(destinationPath));
            }

            if (ct == null)
            {
                throw new ArgumentNullException(nameof(ct));
            }

            return(await Task.Run(
                       () =>
            {
                IList <CompressedEntryModel> entries = new List <CompressedEntryModel>();

                // TODO: add options as parameters
                var options = new ReaderOptions()
                {
                    LeaveStreamOpen = false,
                    LookForHeader = false
                };

                using (var file = File.OpenRead(sourcePath))
                {
                    using (var archive = ArchiveFactory.Open(file, options))
                        using (var comparer = new GenericNaturalComparer <IArchiveEntry>(e => e.Key))
                        {
                            var sortedEntries = archive.Entries.Sort(comparer).Take(MaxCompressibleEntries);
                            foreach (var entry in sortedEntries)
                            {
                                ct.ThrowIfCancellationRequested();

                                if (!entry.IsDirectory)
                                {
                                    // TODO: add options as parameters
                                    var extractionOptions = new ExtractionOptions()
                                    {
                                        ExtractFullPath = false,
                                        Overwrite = false
                                    };

                                    entry.WriteToDirectory(destinationPath, extractionOptions);
                                    entries.Add(EntryMapper.Map(entry));
                                }
                            }
                        }
                }

                return entries;
            }, ct));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Extract to specific directory, retaining filename
        /// </summary>
        public static void WriteToDirectory(string sourceArchive, string destinationDirectory,
                                            ExtractionOptions options = null)
        {
            IArchive archive = Open(sourceArchive);

            foreach (IArchiveEntry entry in archive.Entries)
            {
                entry.WriteToDirectory(destinationDirectory, options);
            }
        }
Exemplo n.º 14
0
 public IpdaController()
 {
     _uploadHelper        = new UploadHelper();
     _preservationService = new PreservationService();
     _extractionOptions   = new ExtractionOptions();
     _extractionOptions.ExtractFullPath  = true;
     _extractionOptions.Overwrite        = true;
     _extractionOptions.PreserveFileTime = true;
     _loggerService = new LoggerService(_logger);
 }
Exemplo n.º 15
0
        public static byte[] ExtractAudioBytes(Vinyl vinyl, ExtractionOptions options)
        {
            var parameters = new ExtractionParameters
            {
                Center     = vinyl.Center,
                GapWidth   = vinyl.GapWidth,
                TrackWidth = vinyl.TrackWidth
            };

            return(ExtractAudioBytes(vinyl, parameters, options));
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        public void ExtractAllFromGz(Stream source, string targetPath, bool overwriteExistingFiles)
        {
            using var reader = GZipReader.Open(source);
            var options = new ExtractionOptions
            {
                ExtractFullPath = true,
                Overwrite       = overwriteExistingFiles
            };

            reader.WriteAllToDirectory(targetPath, options);
        }
        public static bool WriteEntryToDirectoryWithFeedback(
            this IReader reader, string destinationDirectory,
            ExtractionOptions options)
        {
            string destinationFileName;
            var    file = Path.GetFileName(reader.Entry.Key);
            var    fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory);

            options ??= new ExtractionOptions()
            {
                Overwrite = true
            };

            if (options.ExtractFullPath)
            {
                var folder  = Path.GetDirectoryName(reader.Entry.Key);
                var destdir = Path.GetFullPath(Path.Combine(fullDestinationDirectoryPath, folder));

                if (!Directory.Exists(destdir))
                {
                    if (!destdir.StartsWith(fullDestinationDirectoryPath))
                    {
                        throw new ExtractionException("Entry is trying to create a directory outside of the destination directory.");
                    }

                    Directory.CreateDirectory(destdir);
                }

                destinationFileName = Path.Combine(destdir, file);
            }
            else
            {
                destinationFileName = Path.Combine(fullDestinationDirectoryPath, file);
            }

            if (!reader.Entry.IsDirectory)
            {
                destinationFileName = Path.GetFullPath(destinationFileName);

                if (!destinationFileName.StartsWith(fullDestinationDirectoryPath))
                {
                    throw new ExtractionException("Entry is trying to write a file outside of the destination directory.");
                }

                return(reader.WriteEntryToFileWithFeedback(destinationFileName, options));
            }
            else if (options.ExtractFullPath && !Directory.Exists(destinationFileName))
            {
                Directory.CreateDirectory(destinationFileName);
            }

            return(false);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Extract to specific file
 /// </summary>
 public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
                                ExtractionOptions options = null)
 {
     ExtractionMethods.WriteEntryToFile(entry, destinationFileName, options,
                                        (x, fm) =>
     {
         using (FileStream fs = File.Open(destinationFileName, fm))
         {
             entry.WriteTo(fs);
         }
     });
 }
Exemplo n.º 19
0
        /// <summary>
        /// Extracts all from tar.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="targetPath">The target path.</param>
        /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
        public void ExtractAllFromTar(Stream source, string targetPath, bool overwriteExistingFiles)
        {
            using var archive = TarArchive.Open(source);
            using var reader  = archive.ExtractAllEntries();
            var options = new ExtractionOptions
            {
                ExtractFullPath = true,
                Overwrite       = overwriteExistingFiles
            };

            reader.WriteAllToDirectory(targetPath, options);
        }
Exemplo n.º 20
0
        private bool UnZip(string tarFile, List <FileItem> files, string installPath)
        {
            using (var archive = ZipArchive.Open(tarFile, Compress.ReaderOptions))
            {
                try
                {
                    var               entries = archive.Entries.ToDictionary(x => x.Key.Replace("/", "\\"));
                    ZipArchiveEntry   entry;
                    ExtractionOptions extractionOptions = new ExtractionOptions
                    {
                        ExtractFullPath  = true,
                        Overwrite        = true,
                        PreserveFileTime = true
                    };
                    if (entries.ContainsKey(Context.UninstallerKey))
                    {
                        entry = entries[Context.UninstallerKey];
                        var path = Path.Combine(installPath, Context.UninstallerKey);
                        entry.WriteToFile(path, extractionOptions);
                    }
                    foreach (var file in files)
                    {
                        if (entries.TryGetValue(file.Key, out entry))
                        {
                            Watch?.Info($"抽取 [{file.Name}]");
                            var path = file.Path;
                            FileHelper.RemoveReadonly(path);
                            var info = new FileInfo(path);
                            if (!Directory.Exists(info.Directory.FullName))
                            {
                                Directory.CreateDirectory(info.Directory.FullName);
                                newDirs.Push(info.Directory.FullName);
                            }

                            var flag = ExtractionFile(entry, info, file.FileOverride, extractionOptions);
                            if (!flag)
                            {
                                return(false);
                            }
                        }

                        Watch?.AddValue(1);
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    Watch?.Error(e.Message);
                    return(false);
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Gets the extraction options.
 /// </summary>
 /// <returns>ExtractionOptions.</returns>
 public static ExtractionOptions GetExtractionOptions()
 {
     if (extractionOptions == null)
     {
         extractionOptions = new ExtractionOptions()
         {
             ExtractFullPath  = true,
             Overwrite        = true,
             PreserveFileTime = true
         };
     }
     return(extractionOptions);
 }
Exemplo n.º 22
0
    public async Task ExtractAsync(string archivePath, string outputDirectory)
    {
        await using var inStream = _fileService.OpenRead(archivePath);
        using var reader         = ReaderFactory.Open(inStream);

        var options = new ExtractionOptions
        {
            ExtractFullPath = true,
            Overwrite       = true
        };

        reader.WriteAllToDirectory(outputDirectory, options);
    }
Exemplo n.º 23
0
        public void ExtractArchive(string archivePath, string extractTo)
        {
            var extOptions = new ExtractionOptions()
            {
                ExtractFullPath = false,
                Overwrite       = true
            };

            using (var stream = File.OpenRead(archivePath))
                using (var archive = ArchiveFactory.Open(stream))
                    using (var reader = archive.ExtractAllEntries())
                        reader.WriteAllToDirectory(extractTo, extOptions);
        }
Exemplo n.º 24
0
Arquivo: Setup.cs Projeto: NFive/nfpm
        private static void Install(string path, string name, byte[] data)
        {
            Console.WriteLine($"Installing {name}...");

            Directory.CreateDirectory(path);

            var skip = new[]
            {
                "server.cfg",
                "server-tls.crt",
                "server-tls.key",
                "__resource.lua",
                "fxmanifest.lua",
                "nfive.yml",
                "nfive.lock",
                "config/nfive.yml",
                "config/database.yml"
            };

            using (var stream = new MemoryStream(data))
            {
                var sevenZip = SevenZipArchive.IsSevenZipFile(stream);
                stream.Position = 0;

                using (var archive = sevenZip ? SevenZipArchive.Open(stream) : null)
                    using (var reader = sevenZip ? archive.ExtractAllEntries() : ReaderFactory.Open(stream))
                    {
                        while (reader.MoveToNextEntry())
                        {
                            if (reader.Entry.IsDirectory)
                            {
                                continue;
                            }

                            var opts = new ExtractionOptions {
                                ExtractFullPath = true, Overwrite = true, PreserveFileTime = true
                            };

                            if (skip.Contains(reader.Entry.Key) && File.Exists(Path.Combine(path, reader.Entry.Key)))
                            {
                                opts.Overwrite = false;                         // TODO: Prompt to overwrite existing config?
                            }

                            reader.WriteEntryToDirectory(path, opts);
                        }
                    }
            }

            Console.WriteLine();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Extracts all contents of the given archive file to the destination directory
        /// </summary>
        public bool ExtractFiles(string archiveFilePath, string destinationDirectory)
        {
            Progress = 0;

            // Initialize
            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            try {
                // Open reader for all entries
                using (var archive = ArchiveFactory.Open(archiveFilePath))
                {
                    // Closure
                    long archiveSize = new FileInfo(archiveFilePath).Length;

                    // Extract
                    foreach (var entry in archive.Entries)
                    {
                        // Abort check
                        if (AbortChecker())
                        {
                            return(false);
                        }

                        // Extract file
                        try
                        {
                            var extractOptions = new ExtractionOptions {
                                ExtractFullPath = true, Overwrite = true
                            };
                            entry.WriteToDirectory(destinationDirectory, extractOptions);
                            Progress += 100.0 * entry.CompressedSize / archiveSize;
                        }
                        catch (Exception ex)
                        {
                            Logger.Record($"Could not unpack an entry from an archive ({entry})");
                            Logger.Record(ex);
                        }
                    }
                    return(true);
                }
            }
            // Archive is invalid
            catch (InvalidOperationException ex)
            {
                return(false);
            }
        }
Exemplo n.º 26
0
        public void Start(BackgroundWorker worker)
        {
            var options = new ExtractionOptions()
            {
                ExtractFullPath = true,
                Overwrite       = true
            };

            var archive = ArchiveFactory.Open(_config.InstallPackage);

            archive.FilePartExtractionBegin += delegate(object sender, SharpCompress.Common.FilePartExtractionBeginEventArgs e)
            {
                _sizeProgress += e.Size;
                worker.ReportProgress(((int)((_sizeProgress * 95) / _totalSize)), "Extracting: " + e.Name);
            };

            foreach (var entry in archive.Entries)
            {
                _totalSize += entry.Size;
            }

            worker.WorkerReportsProgress = true;
            worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                var backgroundWorker = sender as BackgroundWorker;
                foreach (var entry in archive.Entries)
                {
                    entry.WriteToDirectory(_config.InstallLocation, options);
                }
                worker.ReportProgress(98, "Adding registry entries: ");
                var exePath = Path.Combine(_config.InstallLocation, string.Format("{0}.exe", AppInfo.Name));
                var icoPath = Path.Combine(_config.InstallLocation, "icon.ico");
                if (_config.DesktopShortcut)
                {
                    CreateShortcutHelper.AddShortcutToDesktop(exePath, icoPath);
                }
                if (_config.StartmenuShortcut)
                {
                    CreateShortcutHelper.AddShortcutToStartmenu(exePath, icoPath);
                }
                if (_config.StartOnSystemStart)
                {
                    RegHelper.SetRegRun(exePath);
                }
                RegHelper.SetRegUninstall(_config.InstallLocation, icoPath);
                worker.ReportProgress(100, "Done");
            };
            worker.RunWorkerAsync();
        }
Exemplo n.º 27
0
        private bool Unpack(string file, string unZipTo)
        {
            try
            {
                using (IArchive arc = ArchiveFactory.Open(file))
                {
                    if (!arc.IsComplete)
                    {
                        ErrorDescription = "Update failed: downloaded file is not complete...";
                        return(false);
                    }

                    IReader reader = arc.ExtractAllEntries();

                    // Get number of files...
                    int curentry     = 0;
                    int totalentries = arc.NumEntries;

                    string ourname = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

                    // Unpack all
                    ExtractionOptions options = new ExtractionOptions {
                        ExtractFullPath = true, Overwrite = true
                    };
                    while (reader.MoveToNextEntry())
                    {
                        if (appclosing)
                        {
                            break;
                        }
                        if (reader.Entry.IsDirectory || Path.GetFileName(reader.Entry.Key) == ourname)
                        {
                            continue;                                                                                                   // Don't try to overrite ourselves...
                        }
                        reader.WriteEntryToDirectory(unZipTo, options);
                        UpdateProgressBar(new ByteArgs {
                            Downloaded = curentry++, Total = totalentries
                        }, 1, 2);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorDescription = "Update failed: failed to unpack the update...\n" + e.Message;
                return(false);
            }

            return(true);
        }
Exemplo n.º 28
0
        public void ExtractAllFromGz(Stream source, string targetPath, bool overwriteExistingFiles)
        {
            using (var reader = GZipReader.Open(source))
            {
                var options = new ExtractionOptions();
                options.ExtractFullPath = true;

                if (overwriteExistingFiles)
                {
                    options.Overwrite = true;
                }

                reader.WriteAllToDirectory(targetPath, options);
            }
        }
Exemplo n.º 29
0
        public void UnpackInternal(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder,
            bool overwrite = false, bool fullPath = true, bool checkFileIntegrity = true,
            ITProgress progress = null) {
            Contract.Requires<ArgumentNullException>(sourceFile != null);
            Contract.Requires<ArgumentNullException>(outputFolder != null);

            var ext = sourceFile.FileExtension;
            var options = new ExtractionOptions {PreserveFileTime = true};
            if (fullPath)
                options.ExtractFullPath = true;
            if (overwrite)
                options.Overwrite = true;
            using (var archive = GetArchiveWithGzWorkaround(sourceFile, ext))
                UnpackArchive(outputFolder, overwrite, archive, options, sourceFile);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Extracts all.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="targetPath">The target path.</param>
        /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
        public void ExtractAll(Stream source, string targetPath, bool overwriteExistingFiles)
        {
            using var reader = ReaderFactory.Open(source);
            var options = new ExtractionOptions
            {
                ExtractFullPath = true
            };

            if (overwriteExistingFiles)
            {
                options.Overwrite = true;
            }

            reader.WriteAllToDirectory(targetPath, options);
        }
Exemplo n.º 31
0
        public static void WriteToDirectoryGP(this IArchiveEntry entry, string destinationDirectory, string modName,
                                              ExtractionOptions options = null)
        {
            string destinationFileName;
            string file = Path.GetFileName(entry.Key);
            string fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory);

            options = options ?? new ExtractionOptions()
            {
                Overwrite = true
            };


            if (options.ExtractFullPath)
            {
                string folder  = Path.GetDirectoryName(entry.Key.Replace(modName + "/", "").Replace(modName + "\\", ""));
                string destdir = Path.GetFullPath(
                    Path.Combine(fullDestinationDirectoryPath, folder)
                    );

                if (!Directory.Exists(destdir))
                {
                    if (!destdir.StartsWith(fullDestinationDirectoryPath))
                    {
                        throw new ExtractionException("Entry is trying to create a directory outside of the destination directory.");
                    }

                    Directory.CreateDirectory(destdir);
                }
                destinationFileName = Path.Combine(destdir, file);
            }
            else
            {
                destinationFileName = Path.Combine(fullDestinationDirectoryPath, file);
            }

            if (!entry.IsDirectory)
            {
                destinationFileName = Path.GetFullPath(destinationFileName);

                if (!destinationFileName.StartsWith(fullDestinationDirectoryPath))
                {
                    throw new ExtractionException("Entry is trying to write a file outside of the destination directory.");
                }

                entry.WriteToFile(destinationFileName, options);
            }
        }
Exemplo n.º 32
0
        private void UnpackArchive(IAbsoluteDirectoryPath outputFolder, bool overwrite, IArchive archive,
            ExtractionOptions options, IAbsoluteFilePath sourceFile) {
            foreach (var p in archive.Entries.Where(entry => entry.IsDirectory)
                .Select(entry => outputFolder.GetChildDirectoryWithName(entry.Key)))
                p.MakeSurePathExists();

            foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) {
                var fileName = entry.Key ?? sourceFile.FileNameWithoutExtension;
                var destinationFile = outputFolder.GetChildFileWithName(fileName);
                if (overwrite) {
                    destinationFile.MakeSureParentPathExists();
                    entry.WriteToFile(destinationFile.ToString(), options);
                } else {
                    if (destinationFile.Exists)
                        continue;
                    destinationFile.MakeSureParentPathExists();
                    entry.WriteToFile(destinationFile.ToString(), options);
                }
            }
        }