Example #1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "SevenZip/{account}/{container}/{directory}/{filename}")] HttpRequest req,
            string account, string container, string directory, string filename, ILogger log)
        {
            //Retrieve File from storage
            var lakeClient       = GetDataLakeServiceClient(HttpUtility.UrlDecode(account));
            var fileSystemClient = lakeClient.GetFileSystemClient(HttpUtility.UrlDecode(container));
            DataLakeDirectoryClient directoryClient = fileSystemClient.GetDirectoryClient(HttpUtility.UrlDecode(directory));

            var DownloadFile = directoryClient.GetFileClient(HttpUtility.UrlDecode(filename));
            var ReadStream   = await DownloadFile.OpenReadAsync();

            var response = req.HttpContext.Response;

            response.StatusCode  = 200;
            response.ContentType = "application/json-data-stream";
            using (var archive = SevenZipArchive.Open(ReadStream, null))
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    foreach (IArchiveEntry e in archive.Entries)
                    {
                        e.WriteTo(response.Body);
                    }
                }
            }
            return(new EmptyResult());
        }
Example #2
0
 static void ParseArchive(string archive)
 {
     try
     {
         using (var arch = SevenZipArchive.Open(archive))
         {
             foreach (var ent in arch.Entries)
             {
                 var replayName = Path.GetFileNameWithoutExtension(ent.Key);
                 using (var file = ent.OpenEntryStream())
                 {
                     ParseReplayLog(replayName, file);
                 }
             }
         }
     }
     catch (Exception e)
     {
         exceptions.Writer.TryWrite(Tuple.Create(archive, e));
     }
     if (counterProcessed % 100 == 0)
     {
         Console.WriteLine("Processed {0} parsed {1}", counterProcessed, counterParsed);
     }
 }
Example #3
0
        private bool ExtractZip(string path)
        {
            try
            {
                switch (Path.GetExtension(path).ToLower())
                {
                case ".7z":
                    using (var archive = SevenZipArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                case ".zip":
                    using (var archive = ZipArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                case ".rar":
                    using (var archive = RarArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke("Zip extraction failed: " + ex.Message);
                return(false);
            }

            return(true);
        }
 public static bool EnsureValidArchives(string filePath)
 {
     return(ZipArchive.IsZipFile(filePath) ||
            RarArchive.IsRarFile(filePath) ||
            SevenZipArchive.IsSevenZipFile(filePath) ||
            TarArchive.IsTarFile(filePath));
 }
Example #5
0
        private static void doUpdate(String currentDirectory, String fileName, String downloadURL)
        {
            WebClient clientDL = new WebClient();
            String    file     = currentDirectory + "/" + fileName;

            //file to download to (install directory + file name extracted from html)
            Console.WriteLine("Downloading...");
            clientDL.DownloadFile(downloadURL, file);


            //extract and overwrite
            Console.WriteLine("Extracting...");
            using (var archive = SevenZipArchive.Open(file))
            {
                foreach (var entry in archive.Entries)
                {
                    entry.WriteToDirectory(currentDirectory, new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });
                }
            }

            File.Delete(file);
            Console.WriteLine("Done!");
        }
        public async override Task <DirectoryInfo> Unpack()
        {
            if (packageFile == null || !packageFile.Exists)
            {
                throw new InvalidOperationException();
            }
            string        filePath = packageFile.FullName;
            string        path     = Path.GetDirectoryName(filePath);
            DirectoryInfo dir      = new DirectoryInfo(Path.Combine(path, Path.GetFileNameWithoutExtension(filePath)));

            dir.Create();
            await Task.Run(() =>
            {
                using (Stream stream = File.OpenRead(filePath))
                    using (var archive = SevenZipArchive.Open(stream))
                    {
                        var reader = archive.ExtractAllEntries();
                        while (reader.MoveToNextEntry())
                        {
                            if (!reader.Entry.IsDirectory)
                            {
                                reader.WriteEntryToDirectory(dir.FullName, new ExtractionOptions()
                                {
                                    ExtractFullPath = true,
                                    Overwrite       = true
                                });
                            }
                        }
                    }
            });

            return(dir);
        }
Example #7
0
        private static void doUpdate(String currentDirectory, String result)
        {
            int start = result.IndexOf("https://ci.");
            int end   = result.IndexOf("7z");

            result = result.Substring(start, (end - start) + 2);
            WebClient clientDL = new WebClient();

            int s1 = result.IndexOf("rpcs3");
            int e1 = result.IndexOf("7z");

            String file = currentDirectory + "/" + result.Substring(s1, (e1 - s1) + 2);

            //file to download to (install directory + file name extracted from html)
            Console.WriteLine("Downloading...");
            clientDL.DownloadFile(result, file);


            //extract and overwrite
            Console.WriteLine("Extracting...");
            using (var archive = SevenZipArchive.Open(file))
            {
                foreach (var entry in archive.Entries)
                {
                    entry.WriteToDirectory(currentDirectory, new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });
                }
            }
            System.IO.File.Delete(file);
            Console.WriteLine("Done!");
        }
Example #8
0
 /// <summary>
 /// Constructor with a FileInfo object to an existing file.
 /// </summary>
 /// <param name="fileInfo"></param>
 /// <param name="options"></param>
 public static IArchive Open(FileInfo fileInfo, ReaderOptions options = null)
 {
     fileInfo.CheckNotNull(nameof(fileInfo));
     options = options ?? new ReaderOptions {
         LeaveStreamOpen = false
     };
     using (var stream = fileInfo.OpenRead())
     {
         if (ZipArchive.IsZipFile(stream, null))
         {
             return(ZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (SevenZipArchive.IsSevenZipFile(stream))
         {
             return(SevenZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (GZipArchive.IsGZipFile(stream))
         {
             return(GZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (RarArchive.IsRarFile(stream, options))
         {
             return(RarArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (TarArchive.IsTarFile(stream))
         {
             return(TarArchive.Open(fileInfo, options));
         }
         throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip");
     }
 }
 internal ArchiveEntry(SevenZipArchive archive, string fileName, uint index)
 {
     Debug.Assert(fileName != null, "A file name should be specified.");
     this._archiveReference = new WeakReference(archive);
     this.FileName          = fileName;
     this.Index             = index;
 }
        //TODO
        public override IEnumerable <Test> MakeTestBlocks()
        {
            using (var archive = new SevenZipArchive(_workPath, ArchiveFormat.Unkown, _password))
            {
                var inputFiles = archive.Where(x => InputFilePattern.GetFullRegex().IsMatch(x.FileName));
                var ouputFiles = archive.Where(x => OutputFilePattern.GetFullRegex().IsMatch(x.FileName));
                var comparer   = new TestFileNameComparer(InputFilePattern, OutputFilePattern);

                foreach (var inputFile in inputFiles)
                {
                    foreach (var outputFile in ouputFiles)
                    {
                        var inName  = inputFile.FileName;
                        var outName = outputFile.FileName;

                        if (comparer.Equals(inName, outName))
                        {
                            var idTest = InputFilePattern.GetNumberPart(inName);

                            yield return(new Test(
                                             inputFile.ExtractToStreamReader(),
                                             outputFile.ExtractToStreamReader(),
                                             idTest,
                                             _configTestsetProvider.TimeLimitFor(idTest),
                                             _configTestsetProvider.MemoryLimitFor(idTest),
                                             _configTestsetProvider.PriceFor(idTest)
                                             ));
                        }
                    }
                }
            }
        }
        private CompressionType GetCompressionType(string sourceFile)
        {
            if (SevenZipArchive.IsSevenZipFile(sourceFile))
            {
                return(CompressionType.Sevenzip);
            }

            if (ZipArchive.IsZipFile(sourceFile))
            {
                return(CompressionType.Zip);
            }

            if (GZipArchive.IsGZipFile(sourceFile) && Path.GetExtension(sourceFile).ToLower() == ".gz")
            {
                return(CompressionType.Gzip);
            }

            if (RarArchive.IsRarFile(sourceFile))
            {
                return(CompressionType.Rar);
            }

            if (TarArchive.IsTarFile(sourceFile) && Path.GetExtension(sourceFile).ToLower() == ".tar")
            {
                return(CompressionType.Tar);
            }

            return(CompressionType.None);
        }
Example #12
0
        /// <summary>
        /// Opens an Archive for random access
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="readerOptions"></param>
        /// <returns></returns>
        public static IArchive Open(Stream stream, ReaderOptions?readerOptions = null)
        {
            stream.CheckNotNull(nameof(stream));
            if (!stream.CanRead || !stream.CanSeek)
            {
                throw new ArgumentException("Stream should be readable and seekable");
            }
            readerOptions ??= new ReaderOptions();

            ArchiveType?type;

            IsArchive(stream, out type); //test and reset stream position

            if (type != null)
            {
                switch (type.Value)
                {
                case ArchiveType.Zip:
                    return(ZipArchive.Open(stream, readerOptions));

                case ArchiveType.SevenZip:
                    return(SevenZipArchive.Open(stream, readerOptions));

                case ArchiveType.GZip:
                    return(GZipArchive.Open(stream, readerOptions));

                case ArchiveType.Rar:
                    return(RarArchive.Open(stream, readerOptions));

                case ArchiveType.Tar:
                    return(TarArchive.Open(stream, readerOptions));
                }
            }
            throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip, LZip");
        }
Example #13
0
        public async Task ExtractPackageAsync(byte[] file, string destDirPath, IProgress <double> progress = null, CancellationToken cancellationToken = new CancellationToken())
        {
            long totalSize = file.Length;

            using (Stream memoryStream = new MemoryStream(file))
            {
                if (SevenZipArchive.IsSevenZipFile(memoryStream))
                {
                    // 7z is not a streamable format, thus doesn't function with the ReaderFactory API
                    memoryStream.Position = 0;
                    using (var sevenZipArchive = SevenZipArchive.Open(memoryStream))
                    {
                        var reader = sevenZipArchive.ExtractAllEntries();
                        await ExtractFromReaderAsync(reader, destDirPath, totalSize, progress);
                    }
                }
                else
                {
                    memoryStream.Position = 0;
                    using (var factory = ReaderFactory.Open(memoryStream))
                    {
                        await ExtractFromReaderAsync(factory, destDirPath, totalSize, progress);
                    }
                }
            }
        }
Example #14
0
        private void UnzipFile(ref string psFile)
        {
            try
            {
                this.objLog.GravarLog(Log.TypeMessage.Message, "Unziping file " + psFile);

                string zipFile     = Path.Combine(this.sFilesPath, psFile);
                string unzipedFile = Path.Combine(this.sFilesPath, Path.GetFileNameWithoutExtension(psFile));
                psFile = Path.GetFileNameWithoutExtension(psFile) + ".sta";
                string stafile = Path.Combine(this.sFilesPath, psFile);

                using (SevenZipArchive archive = new SevenZipArchive(zipFile, ArchiveFormat.Zip))//TODO mudar o tipo de zip para Z
                {
                    archive.ExtractAll(this.sFilesPath);
                }

                File.Copy(unzipedFile, stafile, true);
                File.Delete(unzipedFile);
                File.Delete(zipFile);

                this.objLog.GravarLog(Log.TypeMessage.Success, "Unziped file " + psFile);
            }
            catch (Exception ex)
            {
                this.objLog.GravarLog(Log.TypeMessage.Error, ex.Message + " | " + ex.StackTrace);
            }
        }
Example #15
0
        public static MainViewModel GetMainViewModel(IObservable <LogEvent> logEvents)
        {
            var visualizerService = new ExtendedWpfUIVisualizerService();

            visualizerService.Register("TextViewer", typeof(TextViewerWindow));

            IDictionary <PhoneModel, IDeployer> deployerDict = new Dictionary <PhoneModel, IDeployer>
            {
                { PhoneModel.Lumia950Xl, GetDeployer(Path.Combine("Files", "Lumia 950 XL")) },
                { PhoneModel.Lumia950, GetDeployer(Path.Combine("Files", "Lumia 950")) },
            };

            var api            = new LowLevelApi();
            var deployersItems = deployerDict.Select(pair => new DeployerItem(pair.Key, pair.Value)).ToList();
            var importerItems  = new List <DriverPackageImporterItem>()
            {
                new DriverPackageImporterItem("7z",
                                              new DriverPackageImporter <SevenZipArchiveEntry, SevenZipVolume, SevenZipArchive>(
                                                  s => SevenZipArchive.Open(s), "Files")),
                new DriverPackageImporterItem("zip",
                                              new DriverPackageImporter <ZipArchiveEntry, ZipVolume, ZipArchive>(s => ZipArchive.Open(s), "Files"))
            };

            var mainViewModel = new MainViewModel(logEvents, deployersItems, importerItems,
                                                  new ViewServices(new WpfOpenFileService(), DialogCoordinator.Instance, visualizerService),
                                                  async() => new Phone(await api.GetPhoneDisk()));

            return(mainViewModel);
        }
        public int GetEntriesCount()
        {
            switch (Type)
            {
            case ArchiveType.Rar:
                using (var archive = RarArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.Zip:
                using (var archive = ZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.Tar:
                using (var archive = TarArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.SevenZip:
                using (var archive = SevenZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.GZip:
                using (var archive = GZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            default:
                throw new ArgumentOutOfRangeException(nameof(Type), Type, null);
            }
        }
Example #17
0
        /// <summary>
        /// Extracts a 7z archive and returns a list of extracted filenames.
        /// </summary>
        /// <param name="filename">The name of the 7z file.</param>
        /// <returns>The list of file paths to the extracted files.</returns>
        private static string[] ExtractSevenZipArchive(string filename)
        {
            string dir = filename + "-files";

            Directory.CreateDirectory(dir);

            var result = new List <string>();

            using (var archive = SevenZipArchive.Open(filename)) {
                foreach (var entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        Console.Write("Extracting {0} ...", entry.Key);
                        var singleFile = Path.Combine(dir, entry.Key);
                        using (var fs = File.Create(singleFile)) {
                            entry.WriteTo(fs);
                        }
                        result.Add(singleFile);
                        Console.WriteLine(" done.");
                    }
                }
            }

            return(result.ToArray());
        }
Example #18
0
        public async Task Install()
        {
            Console.WriteLine("Getting link to latest ffmpeg");
            string link = await GetLinkFromWebPage();

            Console.WriteLine("Downloading ffmpeg");
            using (MemoryStream stream = await Download(link))
                using (SevenZipArchive archive = SevenZipArchive.Open(stream))
                {
                    Console.WriteLine("Unpacking ffmpeg");
                    string[] files = new string[] { "ffmpeg.exe", "ffprobe.exe" };
                    foreach (string file in files)
                    {
                        SevenZipArchiveEntry f = archive.Entries.First(x => x.Key.Contains(file));
                        string name            = f.Key.Substring(f.Key.LastIndexOf('/') + 1);
                        CheckDirAndCreate(FolderPath);
                        using (Stream entryStream = f.OpenEntryStream())
                            using (FileStream fileStream = File.OpenWrite(Path.Combine(FolderPath, name)))
                                await entryStream.CopyToAsync(fileStream);
                    }
                }
            Console.WriteLine("Update enviroment");
            SetEnvironment();
            Console.WriteLine("Set fontconfig");
            SetFontConfig();
            Console.WriteLine("Copying vp9.exe to " + FolderPath);
            string location = System.Reflection.Assembly.GetEntryAssembly().Location;

            File.Copy(location, Path.Combine(FolderPath, Path.GetFileName(location)));
        }
        public IEnumerable <(string fileName, Stream stream, int size)> GetFiles()
        {
            foreach (var path in _paths)
            {
                var stream  = _fileSystem.File.OpenRead(path);
                var archive =
                    SevenZipArchive.Open(stream);
                var allArchiveEntries = archive.ExtractAllEntries();

                while (allArchiveEntries.MoveToNextEntry())
                {
                    if (allArchiveEntries.Entry.IsDirectory)
                    {
                        continue;
                    }

                    var filename    = allArchiveEntries.Entry.Key.ToLowerInvariant();
                    var entryStream = allArchiveEntries.OpenEntryStream();

                    yield return(
                        filename,
                        entryStream,
                        (int)Math.Min(int.MaxValue, allArchiveEntries.Entry.Size)
                        );
                }
            }
        }
Example #20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] arguments        = Environment.GetCommandLineArgs();
            string   argumentinstring = string.Join(", ", arguments);



            if (argumentinstring.EndsWith(@".zip"))
            {
                using (var archive = ZipArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                //ZipFile.ExtractToDirectory(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1), Path.GetTempPath() + @"ZortosUnzipper");
                MessageBox.Show("Done File Extracted inside" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
            if (argumentinstring.EndsWith(".7z"))
            {
                using (var archive = SevenZipArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                MessageBox.Show("Done File Extracted inside" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
            if (argumentinstring.EndsWith(".rar"))
            {
                using (var archive = RarArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                MessageBox.Show("Done File Extracted inside:" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
        }
Example #21
0
        internal void Extract(string path, System.Threading.CancellationToken token)
        {
            _total            = 0;
            _completed        = 0;
            using var archive = SevenZipArchive.Open(_zipFile);
            //try
            //{
            //    archive.CompressedBytesRead += Archive_CompressedBytesRead;
            _total = archive.Entries.Sum(m => m.Size);
            foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
            {
                token.ThrowIfCancellationRequested();
                entry.WriteToDirectory(path, new ExtractionOptions()
                {
                    ExtractFullPath = true,
                    Overwrite       = true
                });

                _completed += entry.Size;
                UnzipProgressChanged?.Invoke(this, new SevenZipUnzipProgressArgs()
                {
                    Progress = (float)_completed / _total
                });
                //System.Diagnostics.Debug.WriteLine($"{_completed} {_total}");
            }
            //    }
            //    catch (Exception)
            //    {
            //        throw;
            //    }
            //    finally
            //    {
            //        archive.CompressedBytesRead -= Archive_CompressedBytesRead;
            //    }
        }
Example #22
0
 /// <summary>
 /// 读取所有主题文件
 /// </summary>
 /// <param name="name"></param>
 /// <param name="psw"></param>
 public void ReadTheme(string name, string psw)
 {
     using (SevenZipArchive archive = new SevenZipArchive(ThemeMap[name], ArchiveFormat.Unkown, psw))
     {
         XmlTextReader xtr = new XmlTextReader(ExtractToStream(archive, "Theme.xml"));
         GetThemeValue(archive, xtr, name);
     }
 }
 /// <summary>
 /// Constructor used for integrity checks (test mode)
 /// </summary>
 public ArchiveExtractCallback(SevenZipArchive archive, Dictionary <uint, ArchiveEntry> entries, string password)
 {
     _archive     = archive;
     _entries     = entries;
     _password    = string.IsNullOrEmpty(password) ? archive.Password : password;
     _options     = ExtractOptions.NoAbortOnFailure;
     _extractMode = ExtractMode.IntegrityCheck;
 }
 /// <summary>
 /// Constructor used to extract a file to a stream
 /// </summary>
 public ArchiveExtractCallback(SevenZipArchive archive, Dictionary <uint, ArchiveEntry> entries, string password, Stream targetStream, ExtractOptions options)
 {
     _archive      = archive;
     _entries      = entries;
     _password     = string.IsNullOrEmpty(password) ? archive.Password : password;
     _targetStream = targetStream;
     _options      = options;
     _extractMode  = ExtractMode.ExtractToStream;
 }
Example #25
0
        private static bool IsArchive(Stream stream, out ArchiveType?type)
        {
            type = null;
            stream.CheckNotNull(nameof(stream));

            if (!stream.CanRead || !stream.CanSeek)
            {
                throw new ArgumentException("Stream should be readable and seekable");
            }
            if (ZipArchive.IsZipFile(stream, null))
            {
                type = ArchiveType.Zip;
            }
            stream.Seek(0, SeekOrigin.Begin);
            if (type == null)
            {
                if (SevenZipArchive.IsSevenZipFile(stream))
                {
                    type = ArchiveType.SevenZip;
                }
                stream.Seek(0, SeekOrigin.Begin);
            }
            if (type == null)
            {
                if (GZipArchive.IsGZipFile(stream))
                {
                    type = ArchiveType.GZip;
                }
                stream.Seek(0, SeekOrigin.Begin);
            }
            if (type == null)
            {
                if (RarArchive.IsRarFile(stream))
                {
                    type = ArchiveType.Rar;
                }
                stream.Seek(0, SeekOrigin.Begin);
            }
            if (type == null)
            {
                if (TarArchive.IsTarFile(stream))
                {
                    type = ArchiveType.Tar;
                }
                stream.Seek(0, SeekOrigin.Begin);
            }
            if (type == null)                      //test multipartzip as it could find zips in other non compressed archive types?
            {
                if (ZipArchive.IsZipMulti(stream)) //test the zip (last) file of a multipart zip
                {
                    type = ArchiveType.Zip;
                }
                stream.Seek(0, SeekOrigin.Begin);
            }

            return(type != null);
        }
Example #26
0
        /// <summary>
        /// 提取为流格式
        /// </summary>
        /// <param name="source">压缩源</param>
        /// <param name="path">关键字</param>
        /// <returns></returns>
        private Stream ExtractToStream(SevenZipArchive source, string path)
        {
            ArchiveEntry entry  = source[path];
            MemoryStream stream = new MemoryStream();

            entry.Extract(stream);
            stream.Seek(0, SeekOrigin.Begin);
            return(stream);
        }
Example #27
0
 public static Task <bool> ExtractFileAsync(string password, string zipLocation, string unzipLocation, IProgress <int> progress, CancellationToken stop)
 {
     if (zipLocation.EndsWith(".7z") || SevenZipArchive.IsSevenZipFile(zipLocation))
     {
         return(Un7zipFileAsync(password, zipLocation, unzipLocation, progress, stop));
     }
     // default zip
     return(UnzipFileAsync(password, zipLocation, unzipLocation, progress, stop));
 }
 /// <summary>
 /// Constructor used to extract files to the file system
 /// </summary>
 public ArchiveExtractCallback(SevenZipArchive archive, Dictionary <uint, ArchiveEntry> entries, string password, string targetDirectory, ExtractOptions options)
 {
     _archive          = archive;
     _entries          = entries;
     _directoryEntries = new SortedDictionary <string, ArchiveEntry>(new DirectoryNameComparer());
     _password         = string.IsNullOrEmpty(password) ? archive.Password : password;
     _targetDirectory  = targetDirectory;
     _options          = options;
     _extractMode      = ExtractMode.ExtractToFile;
 }
Example #29
0
 private static SevenZipArchive OpenSevenZipArchive(string password, Stream stream)
 {
     if (string.IsNullOrEmpty(password))
     {
         return(SevenZipArchive.Open(stream));
     }
     return(SevenZipArchive.Open(stream, new ReaderOptions {
         Password = password
     }));
 }
Example #30
0
        private static void ExtractNPM(string fileName, string targetFolder)
        {
            Directory.CreateDirectory(targetFolder);

            using (SevenZipArchive archive = new SevenZipArchive(fileName))
            {
                archive.ExtractAll(targetFolder, ExtractOptions.OverwriteExistingFiles);
            }

            Directory.Move(Path.Combine(targetFolder, "package"), Path.Combine(targetFolder, "npm"));
        }
 internal SevenZipArchiveEntry(SevenZipArchive archive, SevenZipFilePart part)
     : base(part)
 {
     this.Archive = archive;
 }
Example #32
0
File: Program.cs Project: saary/nji
        private static string SaveAndExtractPackage(IDictionary<string, object> meta)
        {
            var pkgName = (string)meta["name"];
            var destPath = Path.Combine(ModulesDir, pkgName);
            var url = (string)((IDictionary<string, object>)meta["dist"])["tarball"];
            var urlSplit = url.Split('/');
            var filename = urlSplit[urlSplit.Length - 1];
            var tmpFilePath = Path.Combine(TempDir, filename);
            if (File.Exists(tmpFilePath)) // make sure we don't re-download and reinstall anything
                return destPath;
            Console.WriteLine("Installing {0} into {1} ...", url, destPath);
            CleanUpDir(destPath);
            if (Directory.Exists(destPath))
                Directory.Delete(destPath, true);
            if (!Directory.Exists(TempDir))
                Directory.CreateDirectory(TempDir);
            var tempPkgDir = Path.Combine(TempDir, pkgName);
            if (!Directory.Exists(tempPkgDir))
                Directory.CreateDirectory(tempPkgDir);

            new WebClient().DownloadFile(url, tmpFilePath);

            var workingDir = Environment.CurrentDirectory;
            var tarFileName = Path.Combine(workingDir, tmpFilePath);
            Environment.CurrentDirectory = tempPkgDir;

            using (SevenZipArchive archive = new SevenZipArchive(tarFileName))
            {
                archive.ExtractAll(".", ExtractOptions.OverwriteExistingFiles);
            }

            Environment.CurrentDirectory = workingDir;
            // getting error when doing move, so copy recursively instead
            CopyDirectory(Path.Combine(tempPkgDir, "package"), destPath, true);
            return destPath;
        }
Example #33
0
 private void ZipThread(object msg)
 {
     int index = Int32.Parse(msg.ToString());
     string zipPath = ListLocalZip[index];
     using (SevenZipArchive archive = new SevenZipArchive(zipPath.ToString(), ArchiveFormat.Unkown, ""))
     {
         CoolBar_MaxMaximum = archive.Count;
         for (int i = 0; i < archive.Count; i++)
         {
             ArchiveEntry entry = archive[i];
             string desDir = @"D:\";//文件解压到D盘
             string selfUpdatePath = Directory.GetCurrentDirectory() + "\\seftpatch\\";//自更新的文件临时存放在程序目录下,待程序关闭由其他exe执行复制操作,随后重启计算机
             if (!Directory.Exists(selfUpdatePath))
             {
                 Directory.CreateDirectory(selfUpdatePath);//创建临时存放目录
             }
             if (entry.FileName.ToLower().Contains("ICESetting".ToLower()))//ICESetting的更新文件
             {
                 string st = Directory.GetCurrentDirectory() + "\\seftpatch\\" + entry.FileName;
                 if (entry.IsDirectory)//解压为目录
                 {
                     entry.Extract(selfUpdatePath);
                 }
                 else//解压为文件
                 {
                     int n = 0;
                     while (true)
                     {
                         if (File.Exists(st))
                         {
                             File.Delete(st);
                             WriteLog("已经存在设置文件:需要删除:" + st + ":");
                         }
                         else
                         {
                             break;
                         }
                         n++;
                         if (n > 20)
                         {
                             WriteLog("系统不允许删除");
                             MessageBox.Show("系统不允许删除。");
                         }
                     }
                     try
                     {
                         entry.Extract(selfUpdatePath);
                         WriteLog("写入设置文件:" + selfUpdatePath);
                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                 }
             }
             else//其他程序的更新文件
             {
                 string desSt = desDir + entry.FileName;
                 if (entry.IsDirectory)//是目录
                 {
                     entry.Extract(desDir);
                 }
                 else//是文件
                 {
                     int n = 0;
                     while (true)
                     {
                         if (File.Exists(desSt))
                         {
                             File.Delete(desSt);
                         }
                         else
                         {
                             break;
                         }
                         n++;
                         if (n > 20)
                         {
                             MessageBox.Show("系统不允许删除。");
                         }
                     }
                     try
                     {
                         entry.Extract(desDir);
                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                     WriteLog("解压到其他程序中文件:" + desDir + entry.FileName);
                 }
             }
             CoolBar_ProgressBarContent = "更新文件:" + System.IO.Path.GetFileName(entry.FileName);
             currentNumber = i + 1;
             CoolBar_perCent_Text = string.Format("({0}/{1})", currentNumber, CoolBar.MaxMaximum);
             CoolBar_perCent1_Text = string.Format("({0})", currentNumber, CoolBar.MaxMaximum);
         }
         zipIndex++;
         Console.WriteLine("记录zipIndex:" + zipIndex);
         //WriteLog();
         if (zipIndex != ListLocalZip.Count)
         {
             ZipThread(zipIndex.ToString());
         }
     }
 }
Example #34
0
 /// <summary>
 /// 读取所有主题文件
 /// </summary>
 /// <param name="name"></param>
 /// <param name="psw"></param>
 public void ReadTheme(string name, string psw)
 {
     using (SevenZipArchive archive = new SevenZipArchive(ThemeMap[name], ArchiveFormat.Unkown, psw))
     {
         XmlTextReader xtr = new XmlTextReader(ExtractToStream(archive, "Theme.xml"));
         GetThemeValue(archive, xtr, name);
     }
 }
Example #35
0
 /// <summary>
 /// 获取主题皮肤路径
 /// </summary>
 /// <param name="xtr"></param>
 private Theme GetThemeValue(SevenZipArchive archive, XmlTextReader xtr, string bgName)
 {
     BindingTheme.Name = bgName;
     string content = null;
     while (xtr.Read())
     {
         switch (xtr.NodeType)
         {
             case XmlNodeType.Element:
                 if (xtr.Name.Equals("Bg"))//背景
                 {
                     xtr.MoveToContent();
                     content = xtr.ReadString();
                     BindingTheme.VBG = ExtractToVideoSoruce(archive, content);
                 }
                 else if (xtr.Name.Equals("Image"))
                 {
                     if (xtr.HasAttributes)
                     {
                         for (int i = 0; i < xtr.AttributeCount; i++)
                         {
                             xtr.MoveToAttribute(i);
                             switch (xtr.Value)
                             {
                                 #region MyRegion
                                 case "popBg":
                                     xtr.MoveToContent();
                                     content = xtr.ReadString();
                                     BindingTheme.PopBg = ExtractToImageSource(archive, content);
                                     break;
                                 case "bm":
                                     xtr.MoveToContent();
                                     content = xtr.ReadString();
                                     BindingTheme.Bm = ExtractToImageSource(archive, content);
                                     break;
                                 default:
                                     break;
                                 #endregion
                             }
                         }
                     }
                 }
                 break;
             default:
                 break;
         }
     }
     xtr.Close();
     return BindingTheme;
 }
Example #36
0
        /// <summary>
        /// 提取视频格式
        /// </summary>
        /// <param name="source"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        private Uri ExtractToVideoSoruce(SevenZipArchive source, string path)
        {
            ArchiveEntry entry = source[path];
            string cachestring = Directory.GetCurrentDirectory() + "\\Cache";
            entry.Extract(cachestring);
            string name = System.IO.Path.Combine(cachestring, path);
            string parserName = System.IO.Path.Combine(cachestring, "cache_" + GetSystemDateString() + Path.GetExtension(path));
            (new FileInfo(name)).MoveTo(parserName);

            return new Uri(parserName);
        }
Example #37
0
 private string ExtractToVideoSoruce(SevenZipArchive source, string path, string extension, string moveName)
 {
     ArchiveEntry entry = source[path];
     string cachePath = Directory.GetCurrentDirectory() + "\\Cache";
     if (!Directory.Exists(cachePath))
     {
         Directory.CreateDirectory(cachePath);
     }
     string cachestring = cachePath;
     entry.Extract(cachestring);
     string name = System.IO.Path.Combine(cachestring, path);
     string parserName = System.IO.Path.Combine(cachestring, moveName + extension);
     (new FileInfo(name)).MoveTo(parserName);
     return "\\Cache\\" + moveName + extension;
 }
Example #38
0
 /// <summary>
 /// 提取为流格式
 /// </summary>
 /// <param name="source">压缩源</param>
 /// <param name="path">关键字</param>
 /// <returns></returns>
 private Stream ExtractToStream(SevenZipArchive source, string path)
 {
     ArchiveEntry entry = source[path];
     MemoryStream stream = new MemoryStream();
     entry.Extract(stream);
     stream.Seek(0, SeekOrigin.Begin);
     return stream;
 }
Example #39
0
 /// <summary>
 /// 提取为图片源格式
 /// </summary>
 /// <param name="source">压缩源</param>
 /// <param name="path">关键字</param>
 /// <returns></returns>
 private ImageSource ExtractToImageSource(SevenZipArchive source, string path)
 {
     ArchiveEntry entry = source[path];
     MemoryStream stream = new MemoryStream();
     entry.Extract(stream);
     stream.Seek(0, SeekOrigin.Begin);
     ImageSourceConverter isc = new ImageSourceConverter();
     return (ImageSource)isc.ConvertFrom(stream);
 }
Example #40
0
 /// <summary>
 /// 提取为序列图格式
 /// </summary>
 /// <param name="source">压缩源</param>
 /// <param name="path">关键字</param>
 /// <returns></returns>
 private ImageCollection ExtractToImageCollection(SevenZipArchive source, string path)
 {
     ImageCollection collection = new ImageCollection();
     MemoryStream stream;
     foreach (ArchiveEntry entry in source)
     {
         if (!entry.IsDirectory && entry.FileName.Contains(path))
         {
             stream = new MemoryStream();
             entry.Extract(stream);
             collection.Add(stream);
         }
     }
     return collection;
 }
Example #41
0
        internal SevenZipArchiveEntry(int index, SevenZipArchive archive, SevenZipFilePart part)
            : base(part)
        {
			this.Index = index;
            this.archive = archive;
        }
Example #42
0
        private void UncompressFile(string archiveFilename)
        {
            if (!File.Exists(archiveFilename))
            {
                Console.WriteLine("Can't Decompress: {0}", archiveFilename);
            }

            Console.WriteLine("Decompressing: {0}", archiveFilename);

            var path = Path.GetDirectoryName(archiveFilename) ?? string.Empty;

            using (var archive = new SevenZipArchive(archiveFilename))
            {
                foreach (var entry in archive)
                {
                    if (entry.IsDirectory) continue;

                    var filename = entry.FileName.SubstringAfterChar("\\");

                    Console.WriteLine("Extracting File: {0}", filename);

                    var filePath = Path.Combine(path, filename);

                    using (var stream = File.Create(filePath))
                    {
                        entry.Extract(stream, ExtractOptions.OverwriteExistingFiles);

                        stream.Flush();

                        stream.Close();
                    }
                }
            }
        }
Example #43
0
 public void ReadAllTheme(string psw)
 {
     foreach (var item in ThemeMap)
     {
         using (SevenZipArchive archive = new SevenZipArchive(item.Value, ArchiveFormat.Unkown, psw))
         {
             XmlTextReader xtr = new XmlTextReader(ExtractToStream(archive, "Theme.xml"));
             Theme theme = GetThemeValue(archive, xtr, item.Key);
             ThemeDictionary.Add(item.Key, theme);
         }
     }
 }