/// <summary>
        /// Extract to specific directory, retaining filename
        /// </summary>
        public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
                                            ExtractOptions options = ExtractOptions.Overwrite)
        {
            string destinationFileName;
            string file = Path.GetFileName(entry.Key);


            if (options.HasFlag(ExtractOptions.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);
            }
        }
Beispiel #2
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);
            }
        }
Beispiel #3
0
        public static void Save(this IArchiveEntry archive, string path)
        {
            if (!File.Exists(path))
            {
                archive.WriteToFile(path);
            }
            else
            {
                var imageInfo = new FileInfo(path);

                if (imageInfo.Length != archive.Size)
                {
                    File.Delete(path);

                    archive.WriteToFile(path);
                }
            }
        }
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = Path.GetFileName(currentEntry.Key);
            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                currentEntry.WriteToFile(dlg.FileName);
            }
        }
Beispiel #5
0
        string extractFile(IArchive extractor, IArchiveEntry selectedEntry, string extractionPath, ExecutorLaunchProgressHandler progressHandler = null)
        {
            if (progressHandler != null)
            {
                progressHandler("Creating directory...", 0);
            }

            if (!createExtractionDirectory(extractionPath, selectedEntry.FilePath))
            {
                Logger.LogError("Goodmerge: Unable to find alternate extract directory, hard-coded limit has been reached - check '{0}' for any leftover files", GoodmergeTempPath);
                throw new ExtractException(Translator.Instance.goodmergefileerror);
            }

            Logger.LogDebug("Goodmerge: Extracting file '{0}' to directory '{1}'...", selectedEntry.FilePath, extractionPath);
            if (progressHandler != null)
            {
                progressHandler("Extracting...", 0);
                long totalSize = selectedEntry.Size;

                extractor.EntryExtractionBegin += (sender, e) =>
                {
                    Logger.LogDebug("EntryExtractionBegin {0}", e.Item.FilePath);
                };
                extractor.FilePartExtractionBegin += (sender, e) =>
                {
                    Logger.LogDebug("FilePartExtractionBegin {0}, compressed: {1}kb, total: {2}kb", e.Name, e.CompressedSize / 1024, e.Size / 1024);
                };
                extractor.CompressedBytesRead += (sender, e) =>
                {
                    Logger.LogDebug("CompressedBytesRead {0}, current: {1}kb, total: {2}kb", e.CurrentFilePartCompressedBytesRead / 1024, e.CompressedBytesRead / 1024);
                    int perc = (int)((e.CurrentFilePartCompressedBytesRead * 100) / totalSize);
                    progressHandler(string.Format("Extracting ({0}%)...", perc), perc);
                };
                extractor.EntryExtractionEnd += (sender, e) =>
                {
                    Logger.LogDebug("Extraction complete {0}", e.Item.FilePath);
                    progressHandler("Extraction complete...", 100);
                };
            }

            Logger.LogDebug("Extracting {0}, {1}kb", selectedEntry.FilePath, selectedEntry.Size / 1024);
            string outputFile = Path.Combine(extractionPath, selectedEntry.FilePath);

            try
            {
                selectedEntry.WriteToFile(outputFile);
            }
            catch (Exception ex)
            {
                Logger.LogError("Goodmerge: Error extracting to directory '{0}' - {1}", extractionPath, ex.Message);
                throw new ExtractException(Translator.Instance.goodmergeextracterror);
            }
            return(outputFile);
        }
Beispiel #6
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);
            }
        }
        public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory, ExtractOptions options = 1)
        {
            string destinationFileName = string.Empty;
            string fileName            = Path.GetFileName(entry.FilePath);

            if (!options.HasFlag(ExtractOptions.ExtractFullPath))
            {
                destinationFileName = Path.Combine(destinationDirectory, fileName);
            }
            else
            {
                string directoryName = Path.GetDirectoryName(entry.FilePath);
                string path          = Path.Combine(destinationDirectory, directoryName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                destinationFileName = Path.Combine(path, fileName);
            }
            entry.WriteToFile(destinationFileName, options);
        }
Beispiel #8
0
        private async Task <List <CompressFileUploadOutput> > ArchiveEntryRead(IArchiveEntry entry, ReaderOptions readerOptions,
                                                                               string compressFolder)
        {
            var lstFileInfo = new List <CompressFileUploadOutput>();
            var entryKey    = entry.Key;

            var fileExt      = Path.GetExtension(entryKey).ToLower();
            var tempFilePath = Path.Combine(_tempDir, $"{Guid.NewGuid().ToString("N").ToUpper()}{fileExt}");

            entry.WriteToFile(tempFilePath);

            var fileFolder = CombinePath(compressFolder, Path.GetDirectoryName(entryKey));

            if (IsPackage(fileExt))
            {
                //压缩包的文件名作为一层目录结构,并在后面加 ? 用于表示该一层目录为压缩包,主要为了区分文件夹名为test.rar情况
                var childerFolder = CombinePath(fileFolder, $"{Path.GetFileName(entryKey)}?");

                var childFileInfos = await ArchiveFileRead(tempFilePath, readerOptions, childerFolder);

                lstFileInfo.AddRange(childFileInfos);

                return(lstFileInfo);
            }

            var uploadFileInfo = new CompressFileUploadOutput
            {
                TempFilePath = tempFilePath,
                FileName     = Path.GetFileName(entryKey),
                FolderPath   = fileFolder?.Replace('\\', '/'), //层级机构统一使用 / ,不同的压缩格式,解压的路径Key分隔符不同
                FileMd5      = CalcMd5(tempFilePath)
            };

            lstFileInfo.Add(uploadFileInfo);

            return(lstFileInfo);
        }
Beispiel #9
0
 /// <summary>
 /// Extract to specific file
 /// </summary>
 public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
                                ExtractOptions options = ExtractOptions.Overwrite)
 {
     entry.WriteToFile(destinationFileName, new NullExtractionListener(), options);
 }
        /// <summary>
        /// Begins the file extraction.
        /// </summary>
        /// <param name="file">The file within the archive.</param>
        /// <param name="archive">The archive.</param>
        private void ExtractFile(IArchiveEntry file, IArchive archive)
        {
            _ext = Path.Combine(Path.GetDirectoryName(_file), Path.GetFileName(file.FilePath));
            _active = true;
            _tdstr = "Extracting file...";
            var mthd = new Thread(() => TaskDialog.Show(new TaskDialogOptions
                {
                    Title                   = "Extracting...",
                    MainInstruction         = Path.GetFileName(file.FilePath),
                    Content                 = _tdstr,
                    CustomButtons           = new[] { "Cancel" },
                    ShowProgressBar         = true,
                    EnableCallbackTimer     = true,
                    AllowDialogCancellation = true,
                    Callback                = (dialog, args, data) =>
                        {
                            dialog.SetProgressBarPosition(_tdpos);
                            dialog.SetContent(_tdstr);

                            if (args.ButtonId != 0)
                            {
                                if (_active)
                                {
                                    try { _thd.Abort(); _thd = null; } catch { }

                                    if (!string.IsNullOrWhiteSpace(_ext) && File.Exists(_ext))
                                    {
                                        new Thread(() =>
                                            {
                                                Thread.Sleep(1000);
                                                try { File.Delete(_ext); } catch { }
                                            }).Start();
                                    }
                                }

                                return false;
                            }

                            if (!_active)
                            {
                                dialog.ClickButton(500);
                                return false;
                            }

                            return true;
                        }
                }));
            mthd.SetApartmentState(ApartmentState.STA);
            mthd.Start();

            var total = file.Size;
            var last = DateTime.MinValue;

            archive.CompressedBytesRead += (sender, args) =>
                {
                    if (args.CurrentFilePartCompressedBytesRead == total)
                    {
                        return;
                    }

                    if ((DateTime.Now - last).TotalMilliseconds < 150)
                    {
                        return;
                    }

                    last = DateTime.Now;

                    var perc = ((double)args.CurrentFilePartCompressedBytesRead / (double)total) * 100;
                    _tdpos = (int)perc;
                    _tdstr = "Extracting file: " + Utils.GetFileSize(args.CurrentFilePartCompressedBytesRead) + " / " + perc.ToString("0.00") + "% done...";
                };
            archive.EntryExtractionEnd += (sender, args) =>
                {
                    _active = false;

                    if (!File.Exists(_ext))
                    {
                        return;
                    }

                    new Thread(() =>
                        {
                            Thread.Sleep(250);
                            Utils.Run(_ext);

                            Thread.Sleep(10000);
                            AskAfterUse();
                        }).Start();
                };

            _thd = new Thread(() => file.WriteToFile(_ext));
            _thd.Start();
        }
        /// <summary>
        /// Extracts the file from the archive with the passed key.
        /// </summary>
        /// <param name="node">The node to install the file from.</param>
        /// <param name="path">The path to install the file to.</param>
        /// <param name="silent">Determines if info messages should be added displayed.</param>
        private static void ExtractFile(ModNode node, string path, bool silent = false, bool overrideOn = false)
        {
            if (node == null)
            {
                return;
            }

            string destination = path;

            if (!string.IsNullOrEmpty(destination))
            {
                destination = KSPPathHelper.GetAbsolutePath(destination);
            }

            using (IArchive archive = ArchiveFactory.Open(node.ZipRoot.Key))
            {
                IArchiveEntry entry = archive.Entries.FirstOrDefault(e => e.FilePath.Equals(node.Key, StringComparison.CurrentCultureIgnoreCase));
                if (entry == null)
                {
                    return;
                }

                node.IsInstalled = false;
                if (!File.Exists(destination))
                {
                    try
                    {
                        // create new file.
                        entry.WriteToFile(destination);
                        node.IsInstalled = true;

                        if (!silent)
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_FILE_EXTRACTED_0, destination));
                        }
                    }
                    catch (Exception ex)
                    {
                        Messenger.AddError(string.Format(Messages.MSG_FILE_EXTRACTED_ERROR_0, destination), ex);
                    }
                }
                else if (overrideOn)
                {
                    try
                    {
                        // delete old file
                        File.Delete(destination);

                        // create new file.
                        entry.WriteToFile(destination);

                        if (!silent)
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_FILE_EXTRACTED_0, destination));
                        }
                    }
                    catch (Exception ex)
                    {
                        Messenger.AddError(string.Format(Messages.MSG_FILE_EXTRACTED_ERROR_0, destination), ex);
                    }
                }

                node.IsInstalled = File.Exists(destination);
                node.NodeType    = (node.IsInstalled) ? NodeType.UnknownFileInstalled : NodeType.UnknownFile;
            }
        }
Beispiel #12
0
 public Task Download(FileInfo downloadTarget, Progress <double> progressCallback, CancellationToken cancellationToken)
 {
     // todo reimplement with streams to have progress
     return(Task.Run(() => _sourceItem.WriteToFile(downloadTarget.FullName), cancellationToken));
 }
        /// <summary>
        /// Begins the file extraction.
        /// </summary>
        /// <param name="file">The file within the archive.</param>
        /// <param name="archive">The archive.</param>
        private void ExtractFile(IArchiveEntry file, IArchive archive)
        {
            _td = new TaskDialog
                {
                    Title           = "Extracting...",
                    Instruction     = Path.GetFileName(file.FilePath),
                    Content         = "Extracting file...",
                    CommonButtons   = TaskDialogButton.Cancel,
                    ShowProgressBar = true
                };

            _td.Destroyed   += TaskDialogDestroyed;
            _td.ButtonClick += TaskDialogDestroyed;

            new Thread(() => _td.Show()).Start();

            _ext = Path.Combine(Path.GetDirectoryName(_file), Path.GetFileName(file.FilePath));

            var total = file.Size;
            var last = DateTime.MinValue;

            archive.CompressedBytesRead += (sender, args) =>
                {
                    if (args.CurrentFilePartCompressedBytesRead == total)
                    {
                        return;
                    }

                    if ((DateTime.Now - last).TotalMilliseconds < 150)
                    {
                        return;
                    }

                    last = DateTime.Now;

                    var perc = ((double)args.CurrentFilePartCompressedBytesRead / (double)total) * 100;
                    _td.ProgressBarPosition = (int)perc;
                    _td.Content = "Extracting file: " + Utils.GetFileSize(args.CurrentFilePartCompressedBytesRead) + " / " + perc.ToString("0.00") + "% done...";
                };
            archive.EntryExtractionEnd += (sender, args) =>
                {
                    _td.SimulateButtonClick(-1);

                    if (!File.Exists(_ext))
                    {
                        return;
                    }

                    new Thread(() =>
                        {
                            Thread.Sleep(250);
                            Utils.Run(_ext);

                            Thread.Sleep(10000);
                            AskAfterUse();
                        }).Start();
                };

            _thd = new Thread(() => file.WriteToFile(_ext));
            _thd.Start();
        }