Ejemplo n.º 1
0
        private void button3_Click(object sender, EventArgs u)
        {
            OpenFileDialog myDialog = new OpenFileDialog();

            myDialog.Filter          = "Compressed Files(*.ZIP;*.RAR;*.7ZIP)|*.ZIP;*.RAR;*.7ZIP|All files (*.*)|*.*";
            myDialog.CheckFileExists = true;
            myDialog.Multiselect     = false;
            //  myDialog.ShowDialog();

            if (myDialog.ShowDialog() == DialogResult.OK)
            {
                string AddonFile = myDialog.FileName;

                if (File.Exists(AddonFile))
                {
                    // Will always overwrite if target filenames already exist

                    var archive = ArchiveFactory.Open(AddonFile);

                    double totalSize = archive.Entries.Where(e => !e.IsDirectory).Sum(e => e.Size);

                    Thread t = new Thread(new ThreadStart(loading));
                    t.Start();


                    FileStream   fs1    = new FileStream(@"SFM\PuCE\" + Path.GetFileNameWithoutExtension(AddonFile) + ".PuCE", FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(fs1);


                    foreach (var entry in archive.Entries)
                    {
                        if (!entry.IsDirectory)
                        {
                            Console.WriteLine(entry.FilePath);
                            entry.WriteToDirectory(SFMPATH, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);

                            completed += entry.Size;
                            totalVal   = totalSize;
                            var percentage = completed / totalSize;

                            if (entry.FilePath.EndsWith(@"l"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"t"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"f"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"d"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"x"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"y"))
                            {
                                if (File.Exists(SFMPATH + @"\" + Path.GetFileName(entry.FilePath)))
                                {
                                    Console.WriteLine(SFMPATH + @"\" + Path.GetFileName(entry.FilePath));
                                    writer.Write(@"scripts/sfm/animset/" + Path.GetFileName(entry.FilePath) + "\n");

                                    if (!File.Exists(SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath)))
                                    {
                                        File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath));
                                    }
                                    else
                                    {
                                        DialogResult result2 = MessageBox.Show("File " + Path.GetFileName(entry.FilePath) + " Exists, overwrite this file?", "WARNING", MessageBoxButtons.YesNo);
                                        if (result2 == DialogResult.Yes)
                                        {
                                            File.Delete(SFMPATH + @"\scripts\sfm\animset\" + Path.GetFileName(entry.FilePath));
                                            File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath));
                                        }
                                    }
                                }//End First If
                                else
                                {
                                    writer.Write(entry.FilePath + "\n");
                                }
                            }//END
                            if (entry.FilePath.EndsWith("p"))
                            {
                                if (File.Exists(SFMPATH + @"\" + Path.GetFileName(entry.FilePath)))
                                {
                                    writer.Write(@"maps/" + Path.GetFileName(entry.FilePath) + "\n");

                                    if (!File.Exists(SFMPATH + @"\maps\" + Path.GetFileName(entry.FilePath)))
                                    {
                                        File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"\maps\" + Path.GetFileName(entry.FilePath));
                                    }
                                    else
                                    {
                                        Console.WriteLine("Map" + Path.GetFileName(entry.FilePath) + "Exists, Writing it to file to be able to delete though");
                                    }
                                }
                                else
                                {
                                    writer.Write(entry.FilePath + "\n");
                                }
                            }//Map End
                        }
                    }
                    writer.Close();

                    listView1.Items.Clear();
                    AddonList();
                    ListToString();
                }
            }
        }
Ejemplo n.º 2
0
        private void startSettingUpTestbox()
        {
            String testboxLink     = "http://gamemakersgarage.com/LeagueUI.7z";
            String testboxLocation = Path.GetFullPath(Path.Combine(installDirectoryText.Text, "LeagueUI.7z"));

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

            Download.File(testboxLink, testboxLocation, (progress) =>
            {
                installingTestboxLabel.Text = "Downloading Testbox: " + progress + "%";
            }, () =>
            {
                new Thread(() =>
                {
                    Thread.CurrentThread.IsBackground = true;

                    var entryCount      = 0;
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    using (var archive = ArchiveFactory.Open(testboxLocation, new ReaderOptions()
                    {
                        LookForHeader = true
                    }))
                    {
                        var reader = archive.ExtractAllEntries();
                        while (reader.MoveToNextEntry())
                        {
                            if (stopwatch.Elapsed.Milliseconds >= 100)
                            {
                                installingTestboxLabel.Invoke(new Action(() =>
                                {
                                    installingTestboxLabel.Text = $"{Math.Round((double)entryCount / archive.Entries.Count() * 100, 2)}% - {entryCount} / {archive.Entries.Count()} files";
                                }));
                                stopwatch.Restart();
                            }
                            reader.WriteEntryToDirectory(installDirectoryText.Text,
                                                         new ExtractionOptions()
                            {
                                ExtractFullPath    = true,
                                Overwrite          = true,
                                PreserveAttributes = true,
                                PreserveFileTime   = true
                            });
                            entryCount += 1;
                        }
                    }

                    File.Delete(testboxLocation);

                    unzippingProgressLabel.Invoke(new Action(() =>
                    {
                        string desktopDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                        Utility.CreateShortcut("LeagueUI", desktopDirectory, Path.GetFullPath(Path.Combine(installDirectoryText.Text, "LeagueUI", "LeagueUI.exe")), "League Sandbox Matchmaking Client", Path.GetFullPath(Path.Combine(installDirectoryText.Text, "LeagueUI", "assets", "sandbox-app-icon.ico")));
                        installingTestboxLabel.Text = "✔️";
                        startVisualStudioFirstRun();
                    }));
                }).Start();
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Imports the internal.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="importInstance">if set to <c>true</c> [import instance].</param>
        /// <param name="collectionImportResult">The collection import result.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        private bool ImportInternal(ModCollectionExporterParams parameters, bool importInstance, out ICollectionImportResult collectionImportResult)
        {
            ICollectionImportResult importResult = null;

            if (importInstance)
            {
                importResult = DIResolver.Get <ICollectionImportResult>();
            }
            if (!importInstance)
            {
                if (Directory.Exists(parameters.ModDirectory))
                {
                    DiskOperations.DeleteDirectory(parameters.ModDirectory, true);
                }
            }

            var result = false;

            int getTotalFileCount()
            {
                var count = 0;

                using var fileStream = File.OpenRead(parameters.File);
                using var reader     = ReaderFactory.Open(fileStream);
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        count++;
                    }
                }
                fileStream.Close();
                fileStream.Dispose();
                return(count);
            }

            void parseUsingReaderFactory()
            {
                double total = getTotalFileCount();

                using var fileStream = File.OpenRead(parameters.File);
                using var reader     = ReaderFactory.Open(fileStream);
                double processed        = 0;
                double previousProgress = 0;

                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        var relativePath = reader.Entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar);
                        if (reader.Entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase))
                        {
                            if (importInstance)
                            {
                                using var entryStream  = reader.OpenEntryStream();
                                using var memoryStream = new MemoryStream();
                                entryStream.CopyTo(memoryStream);
                                memoryStream.Seek(0, SeekOrigin.Begin);
                                using var streamReader = new StreamReader(memoryStream, true);
                                var text = streamReader.ReadToEnd();
                                streamReader.Close();
                                streamReader.Dispose();
                                var model = JsonDISerializer.Deserialize <IModCollection>(text);
                                mapper.Map(model, importResult);
                                importResult.ModNames    = model.ModNames;
                                importResult.Descriptors = model.Mods;
                                result = true;
                                break;
                            }
                        }
                        else
                        {
                            if (!importInstance)
                            {
                                var exportFileName = Path.Combine(relativePath.StartsWith(Common.Constants.ModExportPath + Path.DirectorySeparatorChar) ? parameters.ExportModDirectory : parameters.ModDirectory, relativePath.Replace(Common.Constants.ModExportPath + Path.DirectorySeparatorChar, string.Empty));
                                if (!Directory.Exists(Path.GetDirectoryName(exportFileName)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(exportFileName));
                                }
                                reader.WriteEntryToFile(exportFileName, ZipExtractionOpts.GetExtractionOptions());
                            }
                        }
                        processed++;
                        var perc = GetProgressPercentage(total, processed, 100);
                        if (perc != previousProgress)
                        {
                            messageBus.Publish(new ModExportProgressEvent(perc));
                            previousProgress = perc;
                        }
                    }
                }
            }

            void parseUsingArchiveFactory()
            {
                using var fileStream = File.OpenRead(parameters.File);
                using var reader     = ArchiveFactory.Open(fileStream);
                var    entries = reader.Entries.Where(entry => !entry.IsDirectory);
                double total   = !importInstance?entries.Count() : 1;

                double processed        = 0;
                double previousProgress = 0;

                foreach (var entry in entries)
                {
                    var relativePath = entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar);
                    if (entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase))
                    {
                        if (importInstance)
                        {
                            using var entryStream  = entry.OpenEntryStream();
                            using var memoryStream = new MemoryStream();
                            entryStream.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            using var streamReader = new StreamReader(memoryStream, true);
                            var text = streamReader.ReadToEnd();
                            streamReader.Close();
                            streamReader.Dispose();
                            var model = JsonDISerializer.Deserialize <IModCollection>(text);
                            mapper.Map(model, importResult);
                            importResult.ModNames    = model.ModNames;
                            importResult.Descriptors = model.Mods;
                            result = true;
                            break;
                        }
                    }
                    else
                    {
                        if (!importInstance)
                        {
                            var exportFileName = Path.Combine(relativePath.StartsWith(Common.Constants.ModExportPath + Path.DirectorySeparatorChar) ? parameters.ExportModDirectory : parameters.ModDirectory, relativePath.Replace(Common.Constants.ModExportPath + Path.DirectorySeparatorChar, string.Empty));
                            if (!Directory.Exists(Path.GetDirectoryName(exportFileName)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(exportFileName));
                            }
                            entry.WriteToFile(exportFileName, ZipExtractionOpts.GetExtractionOptions());
                        }
                    }
                    processed++;
                    var perc = GetProgressPercentage(total, processed, 100);
                    if (perc != previousProgress)
                    {
                        messageBus.Publish(new ModExportProgressEvent(perc));
                        previousProgress = perc;
                    }
                }
            }

            try
            {
                parseUsingArchiveFactory();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                result = false;
                parseUsingReaderFactory();
            }
            collectionImportResult = importResult;
            return(!importInstance || result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Decompress file to dest dir [Support zip, rar, tar, gzip, 7z].
        /// </summary>
        /// <param name="filePath">Target file.</param>
        /// <param name="destDir">The dest decompress directory.</param>
        /// <param name="clear">Clear the dest dir before decompress.</param>
        /// <param name="progressCallback">Progress callback.</param>
        /// <param name="completeCallback">Complete callback.</param>
        /// <param name="errorCallback">Error callback.</param>
        public void Decompress(string filePath, string destDir, bool clear = false,
                               Action <float> progressCallback             = null,
                               Action <string> completeCallback            = null,
                               Action <string> errorCallback = null)
        {
            if (!File.Exists(filePath))
            {
                var error = string.Format("Decompress file error: Can not find the file in the path {0}", filePath);
                errorCallback?.Invoke(error);
                return;
            }

            if (string.IsNullOrEmpty(destDir))
            {
                var error = "Decompress file error: The dest directory can not be null or empty.";
                errorCallback?.Invoke(error);
                return;
            }

            try
            {
                if (clear)
                {
                    if (Directory.Exists(destDir))
                    {
                        Directory.Delete(destDir, true);
                    }
                }

                using (var archive = ArchiveFactory.Open(filePath))
                {
                    var  totalSize = archive.TotalUncompressSize;
                    long unzipSize = 0;
                    archive.EntryExtractionEnd += (s, e) =>
                    {
                        unzipSize += e.Item.Size;
                        var progress = (float)unzipSize / totalSize;
                        progressCallback?.Invoke(progress);
                    };

                    var options = new ExtractionOptions()
                    {
                        Overwrite          = true,
                        ExtractFullPath    = true,
                        PreserveFileTime   = false,
                        PreserveAttributes = false
                    };

                    foreach (var entry in archive.Entries)
                    {
                        if (!entry.IsDirectory)
                        {
                            entry.WriteToDirectory(destDir, options);
                        }
                    }
                }

                completeCallback?.Invoke(destDir);
            }
            catch (Exception ex)
            {
                var error = string.Format("Decompress file exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
                errorCallback?.Invoke(error);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Moves the downloaded subtitle near the video.
        /// </summary>
        /// <param name="video">The location of the video.</param>
        /// <param name="temp">The location of the downloaded subtitle.</param>
        /// <param name="subtitle">The original file name of the subtitle.</param>
        private void NearVideoFinishMoveOld(string video, string temp, string subtitle)
        {
            if (OpenArchiveTaskDialog.SupportedArchives.Contains(Path.GetExtension(subtitle).ToLower()))
            {
                var archive = ArchiveFactory.Open(temp);
                var files   = archive.Entries.Where(f => !f.IsDirectory && Regexes.KnownSubtitle.IsMatch(f.FilePath)).ToList();

                if (files.Count == 1)
                {
                    using (var mstream = new MemoryStream())
                    {
                        subtitle = Utils.SanitizeFileName(files.First().FilePath.Split('\\').Last());
                        files.First().WriteTo(mstream);

                        try { archive.Dispose(); } catch { }
                        try { File.Delete(temp); } catch { }
                        File.WriteAllBytes(temp, mstream.ToArray());
                    }
                }
                else
                {
                    var dlsnvtd = new TaskDialogOptions
                    {
                        Title                   = "Download subtitle near video",
                        MainInstruction         = _link.Release,
                        Content                 = "The downloaded subtitle was a ZIP package with more than one files.\r\nSelect the matching subtitle file to extract it from the package:",
                        AllowDialogCancellation = true,
                        CommandButtons          = new string[files.Count + 1],
                    };

                    var i = 0;
                    for (; i < files.Count; i++)
                    {
                        dlsnvtd.CommandButtons[i] = files[i].FilePath + "\n" + Utils.GetFileSize(files[i].Size) + "   –   " + files[i].LastModifiedTime;
                    }

                    dlsnvtd.CommandButtons[i] = "None of the above";

                    var res = TaskDialog.Show(dlsnvtd);

                    if (res.CommandButtonResult.HasValue && res.CommandButtonResult.Value < files.Count)
                    {
                        using (var mstream = new MemoryStream())
                        {
                            subtitle = Utils.SanitizeFileName(files[res.CommandButtonResult.Value].FilePath.Split('\\').Last());
                            files[res.CommandButtonResult.Value].WriteTo(mstream);

                            try { archive.Dispose(); } catch { }
                            try { File.Delete(temp); } catch { }
                            File.WriteAllBytes(temp, mstream.ToArray());
                        }

                        NearVideoFinishMoveOld(video, temp, subtitle);
                    }
                    else
                    {
                        _play = false;
                    }

                    return;
                }
            }

            var ext = new FileInfo(subtitle).Extension;

            if (Settings.Get <bool>("Append Language to Subtitle") && Languages.List.ContainsKey(_link.Language))
            {
                ext = "." + Languages.List[_link.Language].Substring(0, 3).ToLower() + ext;
            }

            var dest = Path.ChangeExtension(video, ext);

            if (File.Exists(dest))
            {
                try { File.Delete(dest); } catch { }
            }

            File.Move(temp, dest);
        }
Ejemplo n.º 6
0
        public async void ImportPackage()
        {
            try
            {
                Utils.WriteConsole(String.Format("[Scripts importer] ({0}) Extracting the script package", this.name));
                ChangeStatus(Langs.Importing);

                // Extract the .rar in temp folder
                if (Directory.Exists(Reference.TempPath + this.name))
                {
                    Directory.Delete(Reference.TempPath + this.name, true);
                }
                var archive = ArchiveFactory.Open(this.path);
                archive.WriteToDirectory(Reference.TempPath + this.name, new ExtractionOptions()
                {
                    ExtractFullPath = true, Overwrite = true
                });
                archive.Dispose();

                // Import the package
                foreach (String path in Directory.GetFiles(Reference.TempPath + this.name, "*.*", SearchOption.AllDirectories))
                {
                    // Get relative path
                    String RelativePath = path.Substring(Reference.TempPath.Length + this.name.Length);
                    RelativePath = RelativePath.Replace("{usermap}", Reference.MAP_name);
                    String FinalPath = Reference.BlackOps3Root + RelativePath;

                    // Check if the folder or file exists, existing files can be overwritten
                    if (!Directory.Exists(Path.GetDirectoryName(FinalPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(FinalPath));
                    }
                    if (!Reference.Overwrite.Contains(FinalPath))
                    {
                        File.Copy(path, FinalPath, true); Utils.WriteConsole(String.Format("[Scripts importer] ({0}) A file has been overwritten ({1})", this.name, FinalPath));
                    }
                    else
                    {
                        // Import script code
                        String[] ComplexFile = new String[] { ".gsc", ".csc" };
                        if (ComplexFile.Contains(Path.GetExtension(FinalPath)))
                        {
                            ImportComplexFile(FinalPath, path);
                        }
                        else
                        {
                            String  FinalPathContent = File.ReadAllText(FinalPath).Trim();
                            Boolean AlreadyImported  = true;
                            // Check if the code has not already been imported. (To avoid duplicates)
                            foreach (String codeLine in File.ReadAllText(path).Trim().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None))
                            {
                                if (!FinalPathContent.Contains(codeLine))
                                {
                                    WolfLib.Files.InsertLine(FinalPath, codeLine, File.ReadAllLines(FinalPath).Count()); AlreadyImported = false;
                                }
                            }
                            if (AlreadyImported)
                            {
                                Utils.WriteConsole(String.Format("[Scripts importer] ({0}) The code has already been imported ({1})", this.name, FinalPath));
                            }
                        }
                    }
                }

                // Delete the temp folder
                if (Directory.Exists(Reference.TempPath + this.name))
                {
                    Directory.Delete(Reference.TempPath + this.name, true);
                }

                Utils.WriteConsole(String.Format("[Scripts importer] ({0}) The script package has been successfully imported", this.name));
                Reference.ReloadMAPVariables(Reference.MAP_name);

                // Change the status of the script to "Completed"
                await Task.Delay(1000);

                ChangeStatus(Langs.Completed);
                InProgress = false;
            }
            catch (Exception ex) { Utils.ThrowException(ex); }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip
        /// </summary>
        public void UnpackByEntry()
        {
            //System.IO.Compression.ZipFile.ExtractToDirectory(@"xxx.zip", @"xx\tttt", System.Text.CodePagesEncodingProvider.Instance.GetEncoding("GB2312"), true);

            dirCount       = 0;
            fileCount      = 0;
            sumEntityCount = 0;

            using (var archive = ArchiveFactory.Open(inputPath, readOptions))
            {
                sumEntityCount = archive.Entries.Count();

                if (sumEntityCount == 0)
                {
                    OnProgress?.Invoke(1, 0, 0);
                    return;
                }

                int importedEntityCount = 0;
                int step     = Math.Min((int)(sumEntityCount * progressStep), stepMaxEntityCount);
                int nextStep = step;


                //(法.1)流式读取
                using (var reader = archive.ExtractAllEntries())
                {
                    while (reader.MoveToNextEntry())
                    {
                        var entry = reader.Entry;
                        reader.WriteEntryToDirectory(outputPath, extractionOptions);

                        importedEntityCount++;

                        if (importedEntityCount >= nextStep)
                        {
                            nextStep = Math.Min(sumEntityCount, nextStep + step);
                            OnProgress?.Invoke(1.0f * importedEntityCount / sumEntityCount, sumEntityCount, importedEntityCount);
                        }

                        if (entry.IsDirectory)
                        {
                            dirCount++;
                            OnDir?.Invoke(sumEntityCount, importedEntityCount, entry.Key);
                        }
                        else
                        {
                            fileCount++;
                            OnFile?.Invoke(sumEntityCount, importedEntityCount, entry.Key);
                        }
                    }
                }
                return;


                //(法.2)
                foreach (var entry in archive.Entries)
                {
                    entry.WriteToDirectory(outputPath, extractionOptions);

                    importedEntityCount++;

                    if (importedEntityCount >= nextStep)
                    {
                        nextStep = Math.Min(sumEntityCount, nextStep + step);
                        OnProgress?.Invoke(1.0f * importedEntityCount / sumEntityCount, sumEntityCount, importedEntityCount);
                    }

                    if (entry.IsDirectory)
                    {
                        dirCount++;
                        OnDir?.Invoke(sumEntityCount, importedEntityCount, entry.Key);
                    }
                    else
                    {
                        fileCount++;
                        OnFile?.Invoke(sumEntityCount, importedEntityCount, entry.Key);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private async Task preparing()
        {
            Console.WriteLine("识别文件中的有效图片.");

            string file = Path.Combine(book.Path, book.Name);

            FileInfo f = new FileInfo(file);

            if (!f.Exists)
            {
                Console.WriteLine("文件不存在...");
                return;
            }


            // IArchive archive = null;
            try
            {
                var archive = ArchiveFactory.Open(file);

                Console.WriteLine("开始对内容排序.");

                entries = archive.Entries
                          .Where(a => (!a.IsDirectory && ComicUtils.IsImage(a.Key)))
                          .OrderBy(a => a.Key)
                          .ToList();
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine("打开文件需要密码.");
                Console.WriteLine(ex);
            }


            Console.WriteLine("文件页数:" + entries.Count);

            // 过滤不是图片的压缩包文件,并按文件名排序

            if (book.Count != entries.Count)
            {
                Console.WriteLine("更新页码数.");

                book.Count = entries.Count;

                await bookService.UpdateAsync(book);
            }


            Console.WriteLine("找到[" + entries.Count + "]张图片");

            EntryPaginator.DataSource = entries;

            if (_Paged && book.Index > 0 && book.Index <= entries.Count)
            {
                await EntryPaginator.HandlePageIndexChange(new PaginationEventArgs(book.Index, 1));
            }

            entry = EntryPaginator.Paged().ToList();

            //Console.WriteLine
            await Task.CompletedTask;
        }
 private void Open(string path) => _archive = ArchiveFactory.Open(path);
Ejemplo n.º 10
0
            private void ProcessDownload(object state)
            {
                // check if already finished processing download and call Complete()
                if (HasProcessed)
                {
                    SetPercentComplete?.Invoke(100);
                    Complete();
                    return;
                }

                try
                {
                    string source = Path.Combine(Sys.Settings.LibraryLocation, "temp", FileName);
                    _dest = Path.Combine(Sys.Settings.LibraryLocation, FileName);

                    byte[] sig  = new byte[4];
                    int    isig = 0;
                    using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read))
                    {
                        fs.Read(sig, 0, 4);
                        isig = BitConverter.ToInt32(sig, 0);
                        fs.Close();
                    }

                    if (isig == _7thWrapperLib.IrosArc.SIG)
                    {
                        //plain IRO file, just move into place
                        using (var iro = new _7thWrapperLib.IrosArc(source))
                            if (!iro.CheckValid())
                            {
                                throw new Exception("IRO archive appears to be invalid: corrupted download?");
                            }

                        SetPercentComplete?.Invoke(50);

                        File.Copy(source, _dest, overwrite: true);
                        File.Delete(source);
                    }
                    else
                    {
                        using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read))
                        {
                            var archive = ArchiveFactory.Open(fs);
                            var iroEnt  = archive.Entries.FirstOrDefault(e => Path.GetExtension(e.Key).Equals(".iro", StringComparison.InvariantCultureIgnoreCase));
                            if (iroEnt != null)
                            {
                                SetPercentComplete?.Invoke(50);
                                iroEnt.WriteToFile(_dest, new SharpCompress.Common.ExtractionOptions()
                                {
                                    Overwrite = true
                                });
                            }
                            else
                            {
                                //extract entire archive...
                                if (_dest.EndsWith(".iro", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    _dest = _dest.Substring(0, _dest.Length - 4);
                                }
                                string extractTo = _dest;
                                if (!String.IsNullOrEmpty(ExtractInto))
                                {
                                    extractTo = Path.Combine(extractTo, ExtractInto);
                                }
                                Directory.CreateDirectory(extractTo);

                                using (var reader = archive.ExtractAllEntries())
                                {
                                    var entries = archive.Entries.ToArray();
                                    int count   = 0;
                                    while (reader.MoveToNextEntry())
                                    {
                                        if (!reader.Entry.IsDirectory)
                                        {
                                            reader.WriteEntryToDirectory(extractTo, new ExtractionOptions()
                                            {
                                                ExtractFullPath = true, Overwrite = true
                                            });
                                        }

                                        count++;
                                        float prog = (float)count / (float)entries.Length;
                                        SetPercentComplete?.Invoke((int)(50 * prog) + 50); // start at 50% go up to 100%
                                    }
                                }
                            }
                            fs.Close();
                        }

                        File.Delete(source);
                    }
                }
                catch (Exception e)
                {
                    Error(e);
                    return;
                }


                HasProcessed = true; // if reached this point then successfully processed the download with no error
                SetPercentComplete?.Invoke(100);
                Complete();
            }
Ejemplo n.º 11
0
        private void startUnzippingClient()
        {
            if (Directory.Exists(Path.Combine(installDirectoryText.Text, "League of Legends_UNPACKED")))
            {
                Directory.Move(Path.Combine(installDirectoryText.Text, "League of Legends_UNPACKED"), Path.Combine(installDirectoryText.Text, "League of Legends"));
            }
            if (Directory.Exists(Path.Combine(installDirectoryText.Text, "League of Legends")))
            {
                Directory.Move(Path.Combine(installDirectoryText.Text, "League of Legends"), Path.Combine(installDirectoryText.Text, "League_Sandbox_Client"));
            }
            if (Directory.Exists(Path.Combine(installDirectoryText.Text, "League_Sandbox_Client")))
            {
                unzippingProgressLabel.Text = "✔️";
                startSettingUpTestbox();
                return;
            }

            var localFilePath = Path.Combine(installDirectoryText.Text, Client_Folder_Name + ".7z");

            unzippingProgressLabel.Text = "--";
            var directoryPath = installDirectoryText.Text;

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                var entryCount      = 0;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                using (var archive = ArchiveFactory.Open(localFilePath, new ReaderOptions()
                {
                    LookForHeader = true
                }))
                {
                    var reader = archive.ExtractAllEntries();
                    while (reader.MoveToNextEntry())
                    {
                        if (stopwatch.Elapsed.Milliseconds >= 100)
                        {
                            unzippingProgressLabel.Invoke(new Action(() =>
                            {
                                unzippingProgressLabel.Text = $"{Math.Round((double)entryCount / archive.Entries.Count() * 100, 2)}% - {entryCount} / {archive.Entries.Count()} files";
                            }));
                            stopwatch.Restart();
                        }
                        reader.WriteEntryToDirectory(directoryPath,
                                                     new ExtractionOptions()
                        {
                            ExtractFullPath    = true,
                            Overwrite          = true,
                            PreserveAttributes = true,
                            PreserveFileTime   = true
                        });
                        entryCount += 1;
                    }
                }

                File.Delete(localFilePath);

                unzippingProgressLabel.Invoke(new Action(() =>
                {
                    unzippingProgressLabel.Text = "✔️";
                    startSettingUpTestbox();
                }));
            }).Start();
        }
Ejemplo n.º 12
0
        public NStream OpenNStream(bool readAsDisc)
        {
            if (!File.Exists(this.FilePath))
            {
                throw new HandledException("SourceFile.Open - '{0}' does not exist.", (this.FilePath) ?? "");
            }

            Stream fs = null;

            if (!this.IsArchive)
            {
                try
                {
                    fs = this.OpenStream();
                    NStream nStream = new NStream(new StreamForward(fs, null));
                    nStream.Initialize(readAsDisc);
                    return(nStream);
                }
                catch (Exception ex)
                {
                    throw new HandledException(ex, "SourceFile.OpenNStream '{0}'", this.FilePath ?? "");
                }
            }
            else
            {
                string   arcType = "";
                IArchive archive;
                if (!this.IsSplit)
                {
                    try
                    {
                        arcType = ((this.AllFiles.Length == 0) ? "" : "multipart ") + "archive";
                        archive = ArchiveFactory.Open(this.FilePath); //handles multipart archives
                    }
                    catch (Exception ex)
                    {
                        throw new HandledException(ex, "SourceFile.OpenNStream ({0}) '{1}'", arcType, this.FilePath ?? "");
                    }
                }
                else
                {
                    try
                    {
                        arcType = "split archive";
                        fs      = this.OpenStream();
                        archive = ArchiveFactory.Open(fs); //handles multipart archives
                    }
                    catch (Exception ex)
                    {
                        throw new HandledException(ex, "SourceFile.OpenNStream ({0}) '{1}'", arcType, this.FilePath ?? "");
                    }
                }

                IArchiveEntry ent;
                string        key = "";
                try
                {
                    //zip uses / path separator rar uses \
                    int pathLen = string.IsNullOrEmpty(this.Path) ? 0 : this.Path.Length + 1;
                    ent = archive.Entries.FirstOrDefault(e => e.Key.Length == pathLen + this.Name.Length && e.Key.StartsWith(this.Path) && e.Key.EndsWith(this.Name));
                    if (ent == null)
                    {
                        throw new Exception("Open archive file entry failure");
                    }
                    key = ent.Key;
                }
                catch (Exception ex)
                {
                    throw new HandledException(ex, "SourceFile.OpenNStream ({0}) '{1}' failed to open entry '{2}'", arcType, this.FilePath ?? "", this.Name ?? "");
                }

                try
                {
                    if (ent != null)
                    {
                        NStream nStream = new NStream(new StreamForward((long)ent.Size, ent.OpenEntryStream(), archive));
                        nStream.Initialize(true);
                        return(nStream);
                    }
                }
                catch (Exception ex)
                {
                    throw new HandledException(ex, "SourceFile.OpenNStream ({0}) '{1}' failed to stream entry '{2}'", arcType, this.FilePath ?? "", key ?? "");
                }

                return(null);
            }
        }
        private void LoadFrom(DataLocation dl, bool asreadonly)
        {
			FileAccess access;
			FileShare share;

			isreadonly = asreadonly;

			// Determine if opening for read only
			if (isreadonly)
			{
				// Read only
				access = FileAccess.Read;
				share = FileShare.ReadWrite;
			}
			else
			{
				// Private access
				access = FileAccess.ReadWrite;
				share = FileShare.Read;
			}

			General.WriteLogLine("Opening " + Path.GetExtension(location.location).ToUpper().Replace(".", "") + " resource \"" + location.location + "\"");

            if (!File.Exists(location.location))
                throw new FileNotFoundException("Could not find the file \"" + location.location + "\"", location.location);

            // Make list of all files
            List<DirectoryFileEntry> fileentries = new List<DirectoryFileEntry>();

			// Take the detour with a FileStream because SharpCompress doesn't directly support opening files as read-only
			filestream = File.Open(location.location, FileMode.OpenOrCreate, access, share);

			// Create archive
			archive = ArchiveFactory.Open(filestream);
            archivetype = archive.Type;

            // Random access of 7z archives works TERRIBLY slow in SharpCompress
            if (archivetype == ArchiveType.SevenZip)
            {
                isreadonly = true; // Unsaveable...
                sevenzipentries = new Dictionary<string, byte[]>(StringComparer.Ordinal);

                IReader reader = archive.ExtractAllEntries();
                while (reader.MoveToNextEntry())
                {
                    if (reader.Entry.IsDirectory || !CheckInvalidPathChars(reader.Entry.Key)) continue;

                    MemoryStream s = new MemoryStream();
                    reader.WriteEntryTo(s);
                    sevenzipentries.Add(reader.Entry.Key.ToLowerInvariant(), s.ToArray());
                    fileentries.Add(new DirectoryFileEntry(reader.Entry.Key));
                }
			}
            else
            {
                foreach (IArchiveEntry entry in archive.Entries)
                {
                    if (!entry.IsDirectory && CheckInvalidPathChars(entry.Key))
                        fileentries.Add(new DirectoryFileEntry(entry.Key));
                }
            }

            // Get rid of archive
            archive.Dispose();
            archive = null;

			filestream.Dispose();
			filestream = null;

            // Make files list
            files = new DirectoryFilesList(dl.GetDisplayName(), fileentries);

            // Initialize without path (because we use paths relative to the PK3 file)
            Initialize();

            // We have no destructor
            GC.SuppressFinalize(this);
        }
		internal override bool SaveFile(MemoryStream stream, string filename)
		{
			// Not implemented in SevenZipArchive...
			if(isreadonly || archivetype == ArchiveType.SevenZip) return false;

			// Convert slashes...
			filename = filename.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

			// Check if target file is locked...
			var checkresult = FileLockChecker.CheckFile(location.location);
			if(!string.IsNullOrEmpty(checkresult.Error))
			{
				string errmsg = "Unable to save file \"" + filename + "\" into archive \"" + location.GetDisplayName() + "\".";
				if(checkresult.Processes.Count > 0)
				{
					string processpath = string.Empty;
					try
					{
						// All manner of exceptions are possible here...
						processpath = checkresult.Processes[0].MainModule.FileName;
					}
					catch { }

					errmsg += " Archive is locked by " + checkresult.Processes[0].ProcessName
						+ " (" + (!string.IsNullOrEmpty(processpath) ? "\"" + processpath + "\"" : "")
						+ ", started at " + checkresult.Processes[0].StartTime + ").";
				}
				
				General.ErrorLogger.Add(ErrorType.Error, errmsg);
				return false;
			}

			using(MemoryStream savestream = new MemoryStream())
			{
				using(ZipArchive za = (ZipArchive)ArchiveFactory.Open(location.location))
				{
					if(za == null)
					{
						string errmsg = "Unable to save file \"" + filename + "\" into archive \"" + location.GetDisplayName() + "\". Unable to open target file as a zip archive.";
						General.ErrorLogger.Add(ErrorType.Error, errmsg);
						return false;
					}

					// Find and remove original entry...
					foreach(ZipArchiveEntry entry in za.Entries)
					{
						if(!entry.IsDirectory && entry.Key == filename)
						{
							za.RemoveEntry(entry);
							break;
						}
					}

					// Add new entry and save the archive to stream...
					za.AddEntry(filename, stream, 0L, DateTime.Now);
					za.SaveTo(savestream, CompressionType.Deflate);
				}

				// Replace archive file...
				File.WriteAllBytes(location.location, savestream.ToArray());
			}

			// Rewind the stream (because DirectoryReader/WADReader don't modify stream Position in SaveFile)
			stream.Position = 0;

			return true;
		}
Ejemplo n.º 15
0
        // Mouse on cell? Show some screenshots to remember game!
        void loadImagesThread(object s)
        {
            var code = s.ToString();

            try
            {
                var images = new List <Image>();
                using (var save = new MemoryStream())
                {
                    hakchi.Shell.Execute("cd /var/lib/clover/profiles/0 && tar -cz " + code, null, save, null, 10000, true);
                    save.Seek(0, SeekOrigin.Begin);
                    using (var extractor = ArchiveFactory.Open(save))
                    {
                        using (var tar = new MemoryStream())
                        {
                            extractor.Entries.First().OpenEntryStream().CopyTo(tar);
                            using (var extractorTar = SharpCompress.Archives.Tar.TarArchive.Open(tar))
                            {
                                foreach (var f in extractorTar.Entries)
                                {
                                    if (Path.GetExtension(f.Key).ToLower() == ".png")
                                    {
                                        var o = new MemoryStream();
                                        f.OpenEntryStream().CopyTo(o);
                                        o.Seek(0, SeekOrigin.Begin);
                                        images.Add(Image.FromStream(o));
                                    }
                                }
                            }
                        }
                    }
                }
                Trace.WriteLine("Loaded " + images.Count + " imags");
                if (images.Count == 0)
                {
                    return;
                }
                if (menuOpened)
                {
                    return;             // Right click...
                }
                Invoke(new Action(delegate
                {
                    // Maybe it's too late?
                    var p    = listViewSaves.PointToClient(Cursor.Position);
                    var item = listViewSaves.GetItemAt(p.X, p.Y);
                    if (item == null)
                    {
                        return;               // No rows at all
                    }
                    if (item.SubItems["colCode"].Text != code)
                    {
                        return;                                        // Other item
                    }
                    if (imagesForm == null)
                    {
                        imagesForm = new ImagesForm();
                    }
                    imagesForm.Left = Cursor.Position.X + 5;
                    imagesForm.Top  = Cursor.Position.Y + 5;
                    imagesForm.Text = item.SubItems["colName"].Text;
                    imagesForm.ShowImages(images);
                    imagesForm.Show();
                }));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 16
0
        public Tasker.Conclusion AddGames(Tasker tasker, Object syncObject = null)
        {
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.AddingGames);
            tasker.SetTitle(Resources.AddingGames);
            tasker.SetStatusImage(Resources.sign_cogs);

            // static presets
            NesApplication.ParentForm           = tasker.HostForm;
            NesApplication.NeedPatch            = null;
            NesApplication.Need3rdPartyEmulator = null;
            NesApplication.CachedCoverFiles     = null;
            NesGame.IgnoreMapper           = null;
            SnesGame.NeedAutoDownloadCover = null;

            int total = files.Count();
            int count = 0;
            var gamesWithMultipleArt = new List <NesApplication>();

            foreach (var sourceFileName in files)
            {
                NesApplication app = null;
                try
                {
                    tasker.SetStatus(string.Format(Resources.AddingGame, Path.GetFileName(sourceFileName)));
                    var    fileName = sourceFileName;
                    var    ext      = Path.GetExtension(sourceFileName).ToLower();
                    byte[] rawData  = null;
                    string tmp      = null;
                    if (!asIs && (ext == ".7z" || ext == ".zip" || ext == ".rar" || ext == ".clvg"))
                    {
                        if (ext == ".clvg")
                        {
                            tmp = TempHelpers.getUniqueTempPath();
                            Directory.CreateDirectory(tmp);

                            using (var file = File.OpenRead(sourceFileName))
                                using (var reader = ReaderFactory.Open(file))
                                {
                                    reader.WriteAllToDirectory(tmp, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, PreserveFileTime = true
                                    });
                                }

                            var gameFilesInArchive = Directory.GetFiles(tmp, "*.desktop").Select(o => new DirectoryInfo(o)).Cast <DirectoryInfo>().ToArray();

                            switch (gameFilesInArchive.LongLength)
                            {
                            case 0:
                                // no files found
                                break;

                            case 1:
                                // one file found
                                fileName = gameFilesInArchive[0].FullName;
                                break;

                            default:
                                // multiple files found
                                var r = SelectFile(tasker, gameFilesInArchive.Select(o => o.FullName).ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        else
                        {
                            using (var extractor = ArchiveFactory.Open(sourceFileName))
                            {
                                var filesInArchive     = extractor.Entries;
                                var gameFilesInArchive = new List <string>();
                                foreach (var f in extractor.Entries)
                                {
                                    if (!f.IsDirectory)
                                    {
                                        var e = Path.GetExtension(f.Key).ToLower();
                                        if (e == ".desktop")
                                        {
                                            gameFilesInArchive.Clear();
                                            gameFilesInArchive.Add(f.Key);
                                            break;
                                        }
                                        else if (CoreCollection.Extensions.Contains(e))
                                        {
                                            gameFilesInArchive.Add(f.Key);
                                        }
                                    }
                                }
                                if (gameFilesInArchive.Count == 1) // Only one known file (or app)
                                {
                                    fileName = gameFilesInArchive[0];
                                }
                                else if (gameFilesInArchive.Count > 1) // Many known files, need to select
                                {
                                    var r = SelectFile(tasker, gameFilesInArchive.ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (filesInArchive.Count() == 1) // No known files but only one another file
                                {
                                    fileName = filesInArchive.First().Key;
                                }
                                else // Need to select
                                {
                                    var r = SelectFile(tasker, filesInArchive.Select(f => f.Key).ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                if (fileName != sourceFileName)
                                {
                                    var o = new MemoryStream();
                                    if (Path.GetExtension(fileName).ToLower() == ".desktop" || // App in archive, need the whole directory
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".jpg") || // Or it has cover in archive
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".png") ||
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".ips")    // Or IPS file
                                        )
                                    {
                                        tmp = Path.Combine(tempDirectory, fileName);
                                        Directory.CreateDirectory(tmp);
                                        extractor.WriteToDirectory(tmp, new ExtractionOptions()
                                        {
                                            ExtractFullPath = true, Overwrite = true
                                        });
                                        fileName = Path.Combine(tmp, fileName);
                                    }
                                    else
                                    {
                                        extractor.Entries.Where(f => f.Key == fileName).First().WriteTo(o);
                                        rawData = new byte[o.Length];
                                        o.Seek(0, SeekOrigin.Begin);
                                        o.Read(rawData, 0, (int)o.Length);
                                    }
                                }
                            }
                        }
                    }
                    app = NesApplication.Import(fileName, sourceFileName, rawData, asIs);

                    if (ext == ".clvg")
                    {
                        app.SkipCoreSelect = true;
                    }
                    else
                    {
                        if (app != null && app.CoverArtMatches != null && app.CoverArtMatches.Count() > 1)
                        {
                            gamesWithMultipleArt.Add(app);
                        }
                        NewGames.Add(app);
                    }

                    if (app is ISupportsGameGenie && Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        var lGameGeniePath = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".xml");
                        if (File.Exists(lGameGeniePath))
                        {
                            GameGenieDataBase lGameGenieDataBase = new GameGenieDataBase(app);
                            lGameGenieDataBase.ImportCodes(lGameGeniePath, true);
                            lGameGenieDataBase.Save();
                        }
                    }

                    if (!string.IsNullOrEmpty(tmp) && Directory.Exists(tmp))
                    {
                        Directory.Delete(tmp, true);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(Tasker.Conclusion.Abort);
                    }
                    if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    {
                        Trace.WriteLine(ex.InnerException.Message + ex.InnerException.StackTrace);
                        tasker.ShowError(ex.InnerException, Path.GetFileName(sourceFileName));
                    }
                    else
                    {
                        Trace.WriteLine(ex.Message + ex.StackTrace, Path.GetFileName(sourceFileName));
                        tasker.ShowError(ex);
                    }
                    return(Tasker.Conclusion.Error);
                }
                if (app != null)
                {
                    addedApps.Add(app);
                }
                tasker.SetProgress(++count, total);
            }
            if (gamesWithMultipleArt.Count > 0)
            {
                tasker.HostForm.Invoke(new Action(() => {
                    using (SelectCoverDialog selectCoverDialog = new SelectCoverDialog())
                    {
                        selectCoverDialog.Games.AddRange(gamesWithMultipleArt);
                        selectCoverDialog.ShowDialog(tasker.HostForm);
                    }
                }));
            }
            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 17
0
        public static Archive LoadArchive(FileInfo file)
        {
            IArchive a = ArchiveFactory.Open(file, Options.None);

            return(new Archive(a, a.Type));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 解压上传模板文件
        /// </summary>
        /// <returns></returns>
        public void UploadInstall_POST()
        {
            var          tplRootPath = $"{EnvUtil.GetBaseDirectory()}/templates/";
            var          tempTplPath = tplRootPath + "~.tpl";
            const string jsTip       = "{\"msg\":\"{0}\"}";
            string       resultMessage;

            /*
             * Stream upStrm = Request.Files[0].InputStream;
             *
             * MemoryStream ms = new MemoryStream();
             * byte[] data=new byte[100];
             * int totalReadBytes=0;
             * int readBytes = 0;
             *
             * while (totalReadBytes<upStrm.Length)
             * {
             *  readBytes = upStrm.Read(data,0,data.Length);
             *  ms.Write(data,0, readBytes);
             *  totalReadBytes += readBytes;
             * }
             */

            //保存文件
            var file = Request.FileIndex(0);

            file.Save(tempTplPath);


            var dirIndex   = 0;
            var entryCount = 0;

            var archive = ArchiveFactory.Open(tempTplPath);


            foreach (var entry in archive.Entries)
            {
                ++entryCount;

                if (dirIndex == 0)
                {
                    dirIndex++;
                    var dirName = entry.Key.Split('\\', '/')[0];
                    if (Directory.Exists(tplRootPath + dirName))
                    {
                        resultMessage = "模板已经存在!";
                        goto handleOver;
                    }
                }

                if (!entry.IsDirectory)
                {
                    entry.WriteToDirectory(tplRootPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                }
            }

            if (entryCount == 0)
            {
                resultMessage = "上传的模板不包含任何内容!";
            }
            else
            {
                resultMessage = "模板安装成功!";
            }

handleOver:

            archive.Dispose();
            File.Delete(tempTplPath);
            //重新注册模板
            Cms.Template.Reload();

            Response.WriteAsync(string.Format(jsTip, resultMessage));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 解压模板文件
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public void ExtractZip_POST()
        {
            string       tplRootPath   = String.Format("{0}templates/", AppDomain.CurrentDomain.BaseDirectory);
            string       tempTplPath   = tplRootPath + "~.tpl";
            const string jsTip         = "<script>window.parent.uploadTip('{0}')</script>";
            string       resultMessage = String.Empty;

            /*
             * Stream upStrm = Request.Files[0].InputStream;
             *
             * MemoryStream ms = new MemoryStream();
             * byte[] data=new byte[100];
             * int totalReadBytes=0;
             * int readBytes = 0;
             *
             * while (totalReadBytes<upStrm.Length)
             * {
             *  readBytes = upStrm.Read(data,0,data.Length);
             *  ms.Write(data,0, readBytes);
             *  totalReadBytes += readBytes;
             * }
             */

            //保存文件
            Request.Files[0].SaveAs(tempTplPath);


            int dirIndex   = 0;
            int entryCount = 0;

            IArchive archive = ArchiveFactory.Open(tempTplPath);


            foreach (IArchiveEntry entry in archive.Entries)
            {
                ++entryCount;

                if (dirIndex == 0)
                {
                    dirIndex++;
                    string dirName = entry.FilePath.Split('\\', '/')[0];
                    if (global::System.IO.Directory.Exists(tplRootPath + dirName))
                    {
                        resultMessage = "模板已经存在!";
                        goto handleOver;
                    }
                }

                if (!entry.IsDirectory)
                {
                    entry.WriteToDirectory(tplRootPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                }
            }

            if (entryCount == 0)
            {
                resultMessage = "上传的模板不包含任何内容!";
            }
            else
            {
                resultMessage = "模板安装成功!";
            }


handleOver:

            archive.Dispose();
            global::System.IO.File.Delete(tempTplPath);

            //重新注册模板
            AtNet.Cms.Cms.Template.Register();

            base.Response.Write(String.Format(jsTip, resultMessage));
        }
        protected override bool TryExtractToFolder(FileInfo compressedFileInfo, DirectoryInfo destinationPathInfo)
        {
            if (!destinationPathInfo.Exists)
            {
                try
                {
                    destinationPathInfo.Create();
                }
                catch (IOException)
                {
                    return(false);
                }

                // Update diredctory info, to update the 'Exists' property
                destinationPathInfo = new DirectoryInfo(destinationPathInfo.FullName);
            }

            this.lastProgressArgs             = null;
            this.CurrentExtractingArchiveInfo = compressedFileInfo;
            this.ProgressExtractedBytes       = 0;
            this.ProgressPercentage           = 0;
            this.ExtractionStopwatch          = new Stopwatch();
            this.ExtractionStopwatch.Start();

            using (IArchive archive = ArchiveFactory.Open(this.CurrentExtractingArchiveInfo,
                                                          new ReaderOptions()
            {
                LeaveStreamOpen = false
            }))
            {
                this.UncompressedArchiveSizeInBytes =
                    archive.Entries.Where((entry) => !entry.IsDirectory).Sum((entry) => entry.Size);
            }

            // This following line is expected to throw first chance exceptions, when the file format is not supported by the extraction library. Since there exists no API to test if a file type is supported (or an archive at all), this is the only extensible solution (in case that supported file type list was extended by the library)
            try
            {
                using (Stream stream = File.OpenRead(this.CurrentExtractingArchiveInfo.FullName))
                {
                    this.UncompressedArchiveSizeInBytes = stream.Length;
                    using (IReader archiveReader = ReaderFactory.Open(stream, new ReaderOptions()))
                    {
                        archiveReader.EntryExtractionProgress += SetEntryExtractionProgressOnReaderExtracting;

                        try
                        {
                            while (archiveReader.MoveToNextEntry())
                            {
                                if (!archiveReader.Entry.IsDirectory)
                                {
                                    archiveReader.WriteEntryToDirectory(
                                        destinationPathInfo.FullName,
                                        new ExtractionOptions()
                                    {
                                        ExtractFullPath    = true,
                                        Overwrite          = true,
                                        PreserveAttributes = false,
                                        PreserveFileTime   = false
                                    });
                                }
                            }
                        }
                        finally
                        {
                            archiveReader.EntryExtractionProgress -= SetEntryExtractionProgressOnReaderExtracting;
                        }
                    }
                }
            }
            catch (InvalidFormatException)
            {
                return(false);
            }
            catch (FormatException)
            {
                return(false);
            }
            catch (InvalidOperationException)
            {
                return(false);
            }
            catch (NotSupportedException)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 21
0
        public void DownloadModule(Module module)
        {
            try
            {
                string userModDir      = Path.Combine(Program.BaseDirectoryExternal, "user_mods");
                var    installedModule = GetInstalledModule(module);
                //If module is installed remove it
                if (installedModule != null)
                {
                    foreach (var file in installedModule.InstalledFiles)
                    {
                        try
                        {
                            if (file.EndsWith("\\"))
                            {
                                Directory.Delete(Path.Combine(userModDir, file), true);
                            }
                            else
                            {
                                File.Delete(Path.Combine(userModDir, file));
                            }
                        }
                        catch { }
                    }

                    InstalledItems.Remove(installedModule);
                    installedModule = null;
                }
                switch (module.ModType)
                {
                case ModuleType.hmod:
                {
                    string fileLocation = Path.Combine(userModDir, module.Path.Substring(module.Path.LastIndexOf('/') + 1));

                    if (DownloadFile(module.Path, fileLocation).Start() == Tasker.Conclusion.Success)
                    {
                        installedModule = module.CreateInstalledItem();
                        installedModule.InstalledFiles.Add(module.Path.Substring(module.Path.LastIndexOf('/') + 1));
                        InstalledItems.Add(installedModule);
                    }
                }
                break;

                case ModuleType.compressedFile:
                    var tempFileName = Path.GetTempFileName();
                    if (DownloadFile(module.Path, tempFileName).Start() == Tasker.Conclusion.Success)
                    {
                        using (var extractor = ArchiveFactory.Open(tempFileName))
                        {
                            installedModule = module.CreateInstalledItem();
                            foreach (var file in extractor.Entries)
                            {
                                int index = file.Key.IndexOf('/');
                                if (index != -1)
                                {
                                    var folder = file.Key.Substring(0, index + 1);
                                    if (!installedModule.InstalledFiles.Contains(folder))
                                    {
                                        installedModule.InstalledFiles.Add(folder);
                                        var localFolder = Path.Combine(userModDir, folder);
                                        if (Directory.Exists(localFolder))
                                        {
                                            Directory.Delete(localFolder, true);
                                        }
                                    }
                                }
                                else if (!file.IsDirectory)
                                {
                                    installedModule.InstalledFiles.Add(file.Key);
                                }
                            }
                            extractor.WriteToDirectory(userModDir, new SharpCompress.Common.ExtractionOptions()
                            {
                                ExtractFullPath = true, Overwrite = true
                            });
                            InstalledItems.Add(installedModule);
                        }
                        File.Delete(tempFileName);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Critical error: " + ex.Message + ex.StackTrace, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SaveConfig();
        }
Ejemplo n.º 22
0
        public Tasker.Conclusion SyncOriginalGames(Tasker tasker, Object SyncObject = null)
        {
            tasker.SetTitle(Resources.ResettingOriginalGames);
            tasker.SetStatusImage(Resources.sign_sync);
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.ResettingOriginalGames);

            string desktopEntriesArchiveFile = Path.Combine(Path.Combine(Program.BaseDirectoryInternal, "data"), "desktop_entries.tar");
            string originalGamesPath         = Path.Combine(Program.BaseDirectoryExternal, "games_originals");

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

            if (!File.Exists(desktopEntriesArchiveFile))
            {
                throw new FileLoadException("desktop_entries.tar data file was deleted, cannot sync original games.");
            }

            try
            {
                var defaultGames = ResetAllOriginalGames ? NesApplication.AllDefaultGames.Select(g => g.Key) : NesApplication.CurrentDefaultGames;
                using (var extractor = ArchiveFactory.Open(desktopEntriesArchiveFile))
                    using (var reader = extractor.ExtractAllEntries())
                    {
                        int i = 0;
                        while (reader.MoveToNextEntry())
                        {
                            if (reader.Entry.IsDirectory)
                            {
                                continue;
                            }

                            var code = Path.GetFileNameWithoutExtension(reader.Entry.Key);
                            if (!defaultGames.Contains(code))
                            {
                                continue;
                            }

                            var ext = Path.GetExtension(reader.Entry.Key).ToLower();
                            if (ext != ".desktop") // sanity check
                            {
                                throw new FileLoadException($"invalid file \"{reader.Entry.Key}\" found in desktop_entries.tar data file.");
                            }

                            string path       = Path.Combine(originalGamesPath, code);
                            string outputFile = Path.Combine(path, code + ".desktop");
                            bool   exists     = File.Exists(outputFile);

                            if (exists && !NonDestructiveSync)
                            {
                                Shared.EnsureEmptyDirectory(path);
                                Thread.Sleep(0);
                            }

                            if (!exists || !NonDestructiveSync)
                            {
                                Directory.CreateDirectory(path);

                                // extract .desktop file from archive
                                using (var o = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                                {
                                    reader.WriteEntryTo(o);
                                    o.Flush();
                                    if (!this.ResetAllOriginalGames && !ConfigIni.Instance.OriginalGames.Contains(code))
                                    {
                                        ConfigIni.Instance.OriginalGames.Add(code);
                                    }
                                }

                                // create game temporarily to perform cover search
                                Trace.WriteLine(string.Format($"Resetting game \"{NesApplication.AllDefaultGames[code].Name}\"."));
                                var game = NesApplication.FromDirectory(path);
                                game.FindCover(code + ".desktop");
                                game.Save();
                            }

                            tasker.SetProgress(++i, defaultGames.Count());
                        }
                    }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error synchronizing original games " + ex.Message + ex.StackTrace);
                tasker.ShowError(ex, Resources.ErrorRestoringAllOriginalGames);
                return(Tasker.Conclusion.Error);
            }

            return(Tasker.Conclusion.Success);
        }
Ejemplo n.º 23
0
        //Рекурсивный поиск по файлам в папках
        static void checkFolder(string FolderName, List <string> StringList, string FoundFilePath)
        {
            foreach (string InnerFile in Directory.GetFiles(FolderName))
            {
                //Проход по текстовым файлам внутри папки поиска
                foreach (string StringToSearch in StringList)
                {
                    string FoundString = getStringFromFile(InnerFile, StringToSearch, FoundFilePath);
                    if (FoundString != null)
                    {
                        lock ("WriteToResultFile")
                            using (StreamWriter SW = new StreamWriter(ResultFile, true, Encoding.Default))
                            {
                                SW.WriteLine(FoundString);
                                Console.WriteLine("{0}. Поток {3}. {1} найдено в файле {2}.", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), FoundString.Split('\t')[0], FoundString.Split('\t')[1], Thread.CurrentThread.Name);
                            }
                        FileInfo FI = new FileInfo(InnerFile);
                        try
                        {
                            File.Copy(FI.FullName, trimSeparator(FoundFolder) + "\\" + FI.Name, true);
                        }
                        catch (Exception Ex)
                        {
                            Console.WriteLine("{0}. Ошибка копирования файла. {1}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), Ex.Message);
                            //Console.ReadKey();
                        }
                    }
                }

                //Проверка файлов как zip-архивов
                if (getFieldFromXML("settings.xml", "/Properties", "SearchInZip").ToLower() == "true")
                {
                    string NewWorkingFolder = trimSeparator(Directory.GetCurrentDirectory()) + "\\" + "Thread_" + Thread.CurrentThread.Name + "_" + DateTime.Now.ToString("ddMMyyyy_HHmmssfff");
                    //Console.WriteLine("Создаваемая временная папка - {0}", NewWorkingFolder);
                    //Console.ReadKey();
                    try
                    {
                        using (ZipFile ZFile = new ZipFile(InnerFile))
                        {
                            if (!Directory.Exists(NewWorkingFolder))
                            {
                                Directory.CreateDirectory(NewWorkingFolder);
                            }
                            ZFile.ExtractAll(NewWorkingFolder, ExtractExistingFileAction.OverwriteSilently);
                            FileInfo FI = new FileInfo(InnerFile);
                            checkFolder(NewWorkingFolder, StringList, trimSeparator(FoundFilePath) + "\\" + FI.Name);
                            if (Directory.Exists(NewWorkingFolder))
                            {
                                Directory.Delete(NewWorkingFolder, true);
                            }
                        }
                    }
                    catch (Exception Ex)
                    {
                        //Файл не является zip-архивом
                    }
                }

                //Проверка файлов как архивов всех форматов
                if (getFieldFromXML("settings.xml", "/Properties", "SearchInAllArchives").ToLower() == "true")
                {
                    string NewWorkingFolder = trimSeparator(Directory.GetCurrentDirectory()) + "\\" + "Thread_" + Thread.CurrentThread.Name + "_" + DateTime.Now.ToString("ddMMyyyy_HHmmssfff");
                    try
                    {
                        if (!Directory.Exists(NewWorkingFolder))
                        {
                            Directory.CreateDirectory(NewWorkingFolder);
                        }
                        var Archive = ArchiveFactory.Open(InnerFile);
                        foreach (var Entry in Archive.Entries)
                        {
                            Entry.WriteToDirectory(NewWorkingFolder, ExtractOptions.Overwrite);
                        }
                        FileInfo FI = new FileInfo(InnerFile);
                        checkFolder(NewWorkingFolder, StringList, trimSeparator(FoundFilePath) + "\\" + FI.Name);
                        if (Directory.Exists(NewWorkingFolder))
                        {
                            Directory.Delete(NewWorkingFolder, true);
                        }
                    }
                    catch (Exception Ex)
                    {
                        //Файл не является архивом
                        if (Directory.Exists(NewWorkingFolder))
                        {
                            Directory.Delete(NewWorkingFolder, true);
                        }
                    }
                }
            }

            //Проход по папкам внутри папки поиска
            foreach (string InnerFolder in Directory.GetDirectories(FolderName))
            {
                checkFolder(InnerFolder, StringList, trimSeparator(FoundFilePath) + "\\" + (new DirectoryInfo(InnerFolder)).Name);
            }
        }
        private async Task <IArchive> openArchiveAsync(string filePath)
        {
            Debug.WriteLine("openArchiveAsync");

            return(await Task.Run(() => ArchiveFactory.Open(filePath)));
        }
Ejemplo n.º 25
0
            private void ProcessDownload(object state)
            {
                try
                {
                    string source = System.IO.Path.Combine(Sys.Settings.LibraryLocation, "temp", File);
                    _dest = System.IO.Path.Combine(Sys.Settings.LibraryLocation, File);
                    byte[] sig = new byte[4];
                    using (var fs = new System.IO.FileStream(source, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        fs.Read(sig, 0, 4);
                        int isig = BitConverter.ToInt32(sig, 0);
                        if (isig == _7thWrapperLib.IrosArc.SIG)
                        {
                            //plain IRO file, just move into place
                            fs.Close();
                            using (var iro = new _7thWrapperLib.IrosArc(source))
                                if (!iro.CheckValid())
                                {
                                    throw new Exception("IRO archive appears to be invalid: corrupted download?");
                                }

                            SetPCComplete(50);

                            System.IO.File.Copy(source, _dest, overwrite: true);
                            System.IO.File.Delete(source);
                        }
                        else
                        {
                            var archive = ArchiveFactory.Open(fs);
                            var iroEnt  = archive.Entries.FirstOrDefault(e => System.IO.Path.GetExtension(e.Key).Equals(".iro", StringComparison.InvariantCultureIgnoreCase));
                            if (iroEnt != null)
                            {
                                SetPCComplete(50);
                                iroEnt.WriteToFile(_dest);
                            }
                            else
                            {
                                //extract entire archive...
                                if (_dest.EndsWith(".iro", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    _dest = _dest.Substring(0, _dest.Length - 4);
                                }
                                var    entries   = archive.Entries.ToArray();
                                string extractTo = _dest;
                                if (!String.IsNullOrEmpty(ExtractInto))
                                {
                                    extractTo = System.IO.Path.Combine(extractTo, ExtractInto);
                                }
                                System.IO.Directory.CreateDirectory(extractTo);
                                using (var reader = archive.ExtractAllEntries())
                                {
                                    int count = 0;
                                    while (reader.MoveToNextEntry())
                                    {
                                        if (!reader.Entry.IsDirectory)
                                        {
                                            string filepath = reader.Entry.Key.Replace('/', '\\');
                                            if (String.IsNullOrEmpty(ExtractSubFolder) || filepath.StartsWith(ExtractSubFolder, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                string path = System.IO.Path.Combine(extractTo, filepath.Substring(ExtractSubFolder.Length).TrimStart('\\', '/'));
                                                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                                                using (var fOut = new System.IO.FileStream(path, System.IO.FileMode.Create))
                                                    reader.WriteEntryTo(fOut);
                                            }
                                            count++;
                                            float prog = (float)count / (float)entries.Length;
                                            SetPCComplete((int)(50 * prog) + 50);  // start at 50% go up to 100%
                                        }
                                    }
                                }
                            }
                            fs.Close();
                            System.IO.File.Delete(source);
                        }
                    }
                }
                catch (Exception e)
                {
                    Error(e);
                    return;
                }
                SetPCComplete(100);
                Complete();
            }
Ejemplo n.º 26
0
 private void extractToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (listView1.Items.Count == 0) //If no archive is open or if there's nothing to extract.
     {
         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             fileName = openFileDialog1.FileName;
             var archive = ArchiveFactory.Open(fileName);
             if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
             {
                 maxprogress = archive.Entries.Count();
                 progress    = 0;
                 progressBarForm.maxp(maxprogress);
                 progressBarForm.Show();
                 foreach (var entry in archive.Entries)
                 {
                     entry.WriteToDirectory(folderBrowserDialog1.SelectedPath, new ExtractionOptions()
                     {
                         ExtractFullPath = true,
                         Overwrite       = true
                     });
                     progress += 1;
                 }
                 progressBarForm.Hide();
                 OpenMessageBox("Extraction", "The archive has been successfully extracted.");
             }
         }
     }
     else if (listView1.SelectedItems.Count == 0) //If no items are selected, Zipper will automatically extract all files.
     {
         var archive = ArchiveFactory.Open(fileName);
         if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
         {
             maxprogress = archive.Entries.Count();
             progress    = 0;
             progressBarForm.maxp(maxprogress);
             progressBarForm.StartPosition = FormStartPosition.CenterScreen;
             progressBarForm.Show();
             foreach (var entry in archive.Entries)
             {
                 entry.WriteToDirectory(folderBrowserDialog1.SelectedPath, new ExtractionOptions()
                 {
                     ExtractFullPath = true,
                     Overwrite       = true
                 });
                 progressBarForm.Step();
             }
             progressBarForm.Hide();
             OpenMessageBox("Extraction", "The archive has been successfully extracted.");
         }
     }
     else
     {
         var archive = ArchiveFactory.Open(fileName);
         if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
         {
             maxprogress = listView1.SelectedItems.Count;
             progress    = 0;
             progressBarForm.maxp(maxprogress);
             progressBarForm.StartPosition = FormStartPosition.CenterScreen;
             progressBarForm.Show();
             foreach (var entry in archive.Entries) //Will extract each selected file.
             {
                 foreach (ListViewItem item in listView1.SelectedItems)
                 {
                     if (item.Text.Equals(entry.Key) || dirName + item.Text == entry.Key)
                     {
                         entry.WriteToDirectory(folderBrowserDialog1.SelectedPath, new ExtractionOptions()
                         {
                             ExtractFullPath = true,
                             Overwrite       = true
                         });
                         progressBarForm.Step();
                     }
                 }
             }
             progressBarForm.Hide();
             OpenMessageBox("Extraction", "The archive has been successfully extracted.");
         }
     }
 }
Ejemplo n.º 27
0
        protected IArchiveEntry SelectSubtitle(string lang, string mediaPath, Stream stream, out string selectedFormat)
        {
            _logger?.Info($"SubhdProvider, SelectSubtitle lang: {lang}, mediaPath: {mediaPath}");

            selectedFormat = "";
            lang           = NormailizeLang(lang);

            IArchiveEntry        currentEntry  = null;
            int                  currentScore  = 0;
            List <IArchiveEntry> entriesToSave = new List <IArchiveEntry>();

            using var archive = ArchiveFactory.Open(stream);
            try
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    string key = entry.Key;

                    _logger?.Info($"SubhdProvider, \t process entry: {key}");

                    int score   = 0;
                    int matches = MatchesLang(lang, key);
                    var format  = ExtractFormat(key);

                    if (ASS.Equals(format) || SSA.Equals(format))
                    {
                        score += 0xF;
                    }
                    else if (SRT.Equals(format))
                    {
                        score += 0x8;
                    }
                    else
                    {
                        continue;
                    }

                    entriesToSave.Add(entry);

                    // lang:
                    //  exactly: 0xF0, matches: 0x80, don't known: 0x00
                    // format:
                    //  ass/ssa: 0xF, srt: 0x8
                    if (matches == 1)
                    {
                        score = 0xF0;
                    }
                    else if (matches == 2)
                    {
                        score = 0x80;
                    }
                    else if (matches == 0)
                    {
                        score = 0;
                    }
                    else
                    {
                        continue;
                    }

                    _logger?.Info($"SubhdProvider, \t score: {score}");

                    if (score > currentScore)
                    {
                        currentScore   = score;
                        currentEntry   = entry;
                        selectedFormat = format;
                    }
                }

                //TrySaveSubtitles(mediaPath, entriesToSave.Where(entry => entry != currentEntry));
            }
            catch (InvalidFormatException)
            {
                throw;
            }
            catch (IndexOutOfRangeException)
            {
                throw;
            }

            _logger?.Info($"SubhdProvider, SelectSubtitle selectedEntry: {currentEntry.Key}, format: {selectedFormat}");
            return(currentEntry);
        }
Ejemplo n.º 28
0
        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            List <string> selection = new List <string>();
            var           archive   = ArchiveFactory.Open(fileName);

            Directory.CreateDirectory(Path.GetTempPath() + @"\ZipperTMP\");
            foreach (var entry in archive.Entries)
            {
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    Debug.WriteLine(dirName);
                    if (item.Text.Equals(entry.Key) || dirName + item.Text == entry.Key || item.Text.Equals("./"))
                    {
                        if (!entry.IsDirectory && !item.Text.Equals("./"))
                        {
                            entry.WriteToDirectory(Path.GetTempPath() + @"\ZipperTMP\", new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                            selection.Add(Path.GetTempPath() + @"\ZipperTMP\" + entry.Key);
                            Process tempExtractProcess = new Process
                            {
                                StartInfo = new ProcessStartInfo(Path.GetTempPath() + @"\ZipperTMP\" + entry.Key)
                                {
                                    UseShellExecute = true
                                }
                            };
                            tempExtractProcess.Start();
                        }
                        else
                        {
                            listView1.Items.Clear();
                            if (item.Text.Equals("./"))
                            {
                                Debug.WriteLine(dirName);
                                string preDirName = dirName;
                                if (dirName.EndsWith("/"))
                                {
                                    dirName = dirName.Replace(Path.GetFileName(Path.GetDirectoryName(dirName)) + "/", "");
                                }
                                else if (dirName.EndsWith(@"\"))
                                {
                                    dirName = dirName.Replace(Path.GetFileName(Path.GetDirectoryName(dirName)) + @"\", "");
                                }

                                if (preDirName + @".." == dirName)
                                {
                                    dirName = "";
                                }
                                Debug.WriteLine(dirName);
                            }
                            else
                            {
                                dirName = entry.Key;
                            }
                            if (dirName != "")
                            {
                                ListViewItem lvi = new ListViewItem("./", 1);
                                lvi.SubItems.Add("0");
                                lvi.SubItems.Add("");
                                listView1.Items.Add(lvi);
                            }
                            foreach (var arcentry in archive.Entries)
                            {
                                if (arcentry.Key == dirName + Path.GetFileName(arcentry.Key) ||
                                    arcentry.Key == dirName + "/" + Path.GetDirectoryName(arcentry.Key) + "/" ||
                                    arcentry.Key == dirName + "/" + Path.GetFileName(arcentry.Key) ||
                                    arcentry.Key == dirName + Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) ||
                                    arcentry.Key == dirName + Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) + "/" ||
                                    arcentry.Key == dirName + Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) + @"\" ||
                                    arcentry.Key == dirName + @"\" + Path.GetDirectoryName(arcentry.Key) + @"\" ||
                                    arcentry.Key == dirName + @"\" + Path.GetFileName(arcentry.Key) ||
                                    (Path.GetDirectoryName(arcentry.Key) == dirName + Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) && arcentry.IsDirectory) ||
                                    (Path.GetDirectoryName(arcentry.Key) == dirName + Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) + "/" && arcentry.IsDirectory)
                                    )
                                {
                                    if (arcentry.IsDirectory)
                                    {
                                        //Debug.WriteLine(arcentry.Key);
                                        if (arcentry.Key != dirName)
                                        {
                                            if (arcentry.Key.EndsWith("/"))
                                            {
                                                ListViewItem lvi = new ListViewItem(Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) + "/", 1);
                                                lvi.SubItems.Add(arcentry.Size.ToString("N0"));
                                                lvi.SubItems.Add(arcentry.LastModifiedTime.ToString());
                                                listView1.Items.Add(lvi);
                                            }
                                            else if (arcentry.Key.EndsWith(@"\"))
                                            {
                                                ListViewItem lvi = new ListViewItem(Path.GetFileName(Path.GetDirectoryName(arcentry.Key)) + @"\", 1);
                                                lvi.SubItems.Add(arcentry.Size.ToString("N0"));
                                                lvi.SubItems.Add(arcentry.LastModifiedTime.ToString());
                                                listView1.Items.Add(lvi);
                                            }
                                            else
                                            {
                                                ListViewItem lvi = new ListViewItem(Path.GetFileName(Path.GetDirectoryName(arcentry.Key)), 1);
                                                lvi.SubItems.Add(arcentry.Size.ToString("N0"));
                                                lvi.SubItems.Add(arcentry.LastModifiedTime.ToString());
                                                listView1.Items.Add(lvi);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        ListViewItem lvi = new ListViewItem(Path.GetFileName(arcentry.Key), 1);
                                        lvi.SubItems.Add(arcentry.Size.ToString("N0"));
                                        lvi.SubItems.Add(arcentry.LastModifiedTime.ToString());
                                        listView1.Items.Add(lvi);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <param name="upgradePath"></param>
        /// <param name="resume">是否断点续传</param>
        /// <returns></returns>
        public static int UpgradeFile(string fileName, UpgradeFileType type, string upgradePath, bool resume)
        {
            //检查目录是否存在及权限
            DirectoryInfo dir = new DirectoryInfo(String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, upgradePath));

            if (!dir.Exists)
            {
                Directory.CreateDirectory(dir.FullName).Create();
            }
            else
            {
                //设置权限
                if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
                }
            }

            //断点续传
            byte[] bytes = DownloadFile(fileName, null);
            if (bytes == null)
            {
                return(-1);
            }

            //压缩文件
            if (type == UpgradeFileType.Zip)
            {
                //IArchive archive = ArchiveFactory.Open(file.FullName);
                MemoryStream ms      = new MemoryStream(bytes);
                IArchive     archive = ArchiveFactory.Open(ms);

                foreach (IArchiveEntry entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        entry.WriteToDirectory(dir.FullName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                    }
                }
                archive.Dispose();
                ms.Dispose();
            }
            else
            {
                string dirName = dir.FullName;
                if (type == UpgradeFileType.Lib)
                {
                    // fileName = fileName + ".lib";
                    dirName = Cms.PyhicPath;
                }

                //检查文件是否存在和权限
                FileInfo file = new FileInfo(String.Format("{0}{1}", dirName, fileName));

                if (file.Exists)
                {
                    if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;
                    }
                }
                else
                {
                    file.Create().Dispose();
                }

                //输出到文件
                FileStream fs = file.OpenWrite();
                //  fs.Write(ms.GetBuffer(), 0, (int)ms.Length);
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
                fs.Dispose();
            }

            return(1);
        }
Ejemplo n.º 30
0
        private void listView1_DragDrop(object sender, DragEventArgs u)
        {
            // Extract the data from the DataObject-Container into a string list
            string[] FileList = (string[])u.Data.GetData(DataFormats.FileDrop, false);


            string SFMPATH = ConfigurationManager.AppSettings["SFM_PATH"];

            foreach (string AddonFile in FileList)
            {
                if (File.Exists(AddonFile))
                {
                    SFMLabName = Path.GetFileNameWithoutExtension(AddonFile);
                    SFMLABVersion();
                    // Will always overwrite if target filenames already exist

                    var    archive   = ArchiveFactory.Open(AddonFile);
                    double totalSize = archive.Entries.Where(e => !e.IsDirectory).Sum(e => e.Size);

                    Thread t = new Thread(new ThreadStart(loading));
                    t.Start();


                    FileStream   fs1    = new FileStream(@"SFM\PuCE\" + Path.GetFileNameWithoutExtension(AddonFile) + ".PuCE", FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(fs1);


                    foreach (var entry in archive.Entries)
                    {
                        if (!entry.IsDirectory)
                        {
                            Console.WriteLine(entry.FilePath);
                            entry.WriteToDirectory(SFMPATH, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);

                            completed += entry.Size;
                            totalVal   = totalSize;
                            var percentage = completed / totalSize;

                            //Console.WriteLine(Path.GetFileName(entry.FilePath));
                            //Console.WriteLine(totalSize.ToString());



                            if (entry.FilePath.EndsWith(@"l"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"t"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"f"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"d"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"x"))
                            {
                                writer.Write(entry.FilePath + "\n");
                            }
                            if (entry.FilePath.EndsWith(@"y"))
                            {
                                if (File.Exists(SFMPATH + @"\" + Path.GetFileName(entry.FilePath)))
                                {
                                    Console.WriteLine(SFMPATH + @"\" + Path.GetFileName(entry.FilePath));
                                    writer.Write(@"scripts/sfm/animset/" + Path.GetFileName(entry.FilePath) + "\n");

                                    if (!File.Exists(SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath)))
                                    {
                                        File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath));
                                    }
                                    else
                                    {
                                        DialogResult result2 = MessageBox.Show("File " + Path.GetFileName(entry.FilePath) + " Exists, overwrite this file?", "WARNING", MessageBoxButtons.YesNo);
                                        if (result2 == DialogResult.Yes)
                                        {
                                            File.Delete(SFMPATH + @"\scripts\sfm\animset\" + Path.GetFileName(entry.FilePath));
                                            File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"/scripts/sfm/animset/" + Path.GetFileName(entry.FilePath));
                                        }
                                    }
                                }//End First If
                                else
                                {
                                    writer.Write(entry.FilePath + "\n");
                                }
                            }//END
                            if (entry.FilePath.EndsWith("p"))
                            {
                                if (File.Exists(SFMPATH + @"\" + Path.GetFileName(entry.FilePath)))
                                {
                                    writer.Write(@"maps/" + Path.GetFileName(entry.FilePath) + "\n");

                                    if (!File.Exists(SFMPATH + @"\maps\" + Path.GetFileName(entry.FilePath)))
                                    {
                                        File.Move(SFMPATH + @"\" + Path.GetFileName(entry.FilePath), SFMPATH + @"\maps\" + Path.GetFileName(entry.FilePath));
                                    }
                                    else
                                    {
                                        Console.WriteLine("Map" + Path.GetFileName(entry.FilePath) + "Exists, Writing it to file to be able to delete though");
                                    }
                                }
                                else
                                {
                                    writer.Write(entry.FilePath + "\n");
                                }
                            }//Map End
                        }
                    }
                    writer.Close();

                    listView1.Items.Clear();
                    AddonList();
                    ListToString();
                }
            }
        }