Example #1
0
 static void UnpackArchive(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite,
     bool checkFileIntegrity,
     SevenZipExtractor extracter) {
     if (checkFileIntegrity && !extracter.Check())
         throw new Exception(String.Format("Appears to be an invalid archive: {0}", sourceFile));
     outputFolder.MakeSurePathExists();
     extracter.ExtractFiles(outputFolder.ToString(), overwrite
         ? extracter.ArchiveFileNames.ToArray()
         : extracter.ArchiveFileNames.Where(x => !outputFolder.GetChildFileWithName(x).Exists)
             .ToArray());
 }
Example #2
0
        public Stream Read(CloudFile cloudFile, OnProgress onProgress)
        {
            if (cloudFile.Format == CloudFileFormat.Original)
            {
                return provider.Read(cloudFile, onProgress);
            }
            else
            {
                Stream stream = provider.Read(cloudFile, onProgress);

                using (var decoder = new SevenZip.SevenZipExtractor(stream, password))
                {
                    if (!decoder.Check())
                    {
                        return stream;
                    }
                    else
                    {
                        Stream result = new MemoryStream();
                        if (decoder.FilesCount != 1)
                        {
                            throw new SevenZipProviderException("Cannot extract 7z package which contains no file or more than 1 file.");
                        }

                        decoder.Extracting += new EventHandler<ProgressEventArgs>(
                            (o, p) =>
                            {
                                if (onProgress != null)
                                {
                                    onProgress(cloudFile, ProcessTypes.Decompress, (p.PercentDone * stream.Length), stream.Length);
                                }
                            });

                        decoder.ExtractFile(0, result);
                        stream.Close();
                        result.Position = 0;
                        return result;
                    }
                }
            }
        }
        private void DoCheck()
        {

            string FileName = Explorer.SelectedItems[0].ParsingName;
            SevenZipExtractor extractor = new SevenZipExtractor(FileName);
            if (!extractor.Check())
                MessageBox.Show("Not Pass");
            else
                MessageBox.Show("Pass");

            extractor.Dispose();
        }
Example #4
0
        //where's my async?
        public bool Install(out string err)
        {
            err = null;

            using (var wc = new WebClient())
            {
                Log.File(Localization.RequestingNvsePage, Paths.NvseLink);

                string dlLink;
                using (var resStream = wc.OpenRead(Paths.NvseLink))
                {
                    if (!Util.PatternSearch(resStream, Paths.NvseSearchPattern, out dlLink))
                    {
                        err = Localization.FailedDownloadNvse;
                        return false;
                    }
                }

                Log.File(Localization.ParsedNvseLink, dlLink.Truncate(100));

                var archiveName = Path.GetFileName(dlLink);
                var tmpPath = Path.Combine(Path.GetTempPath(), archiveName);
                wc.DownloadFile(dlLink, tmpPath);

                using (var lzExtract = new SevenZipExtractor(tmpPath))
                {
                    if (!lzExtract.Check())
                    {
                        err = string.Format(Localization.Invalid7zArchive, archiveName);
                        return false;
                    }

                    var wantedFiles = (from file in lzExtract.ArchiveFileNames
                                       let filename = Path.GetFileName(file)
                                       let ext = Path.GetExtension(filename).ToUpperInvariant()
                                       where ext == ".EXE" || ext == ".DLL"
                                       select new { file, filename }).ToArray();

                    foreach (var a in wantedFiles)
                    {
                        var savePath = Path.Combine(_fnvPath, a.filename);
                        Log.File(Localization.Extracting, a.filename);

                        using (var fsStream = File.OpenWrite(savePath))
                        {
                            try
                            {
                                lzExtract.ExtractFile(a.file, fsStream);
                            }
                            catch
                            {
                                err = Localization.FailedExtractNvse;
                                throw;
                            }
                        }
                    }
                }
            }

            Log.Dual(Localization.NvseInstallSuccessful);
            return true;
        }
        public bool Check(string iFileName, string iPassword)
        {
            FileInfo fif = new FileInfo(iFileName);
            if (!fif.Exists)
                throw new ArgumentException();

            using (SevenZipExtractor sze = new SevenZipExtractor(iFileName, iPassword))
            {
                return sze.Check();
            }

        }
        private SevenZipExtractor InstanciateZipExctractorWithPassword(string FileName, IEventListener iel)
        {
            SevenZipExtractor Sex = new SevenZipExtractor(FileName);

            bool valid = Sex.Check();

            if (valid == false)
            {
                Sex.Dispose();

                foreach (string psw in _IUnrarUserSettings.EnumerableRarPasswords)
                {                     
                      Sex = new SevenZipExtractor(FileName, psw);
                      if (Sex.Check())
                      {
                          Trace.WriteLine(string.Format("Find Password in list: {0}", psw));
                          return Sex;
                      }
                      else
                        Sex.Dispose();
                }

                string same = Path.GetFileName(FileName);
                CorruptedRarOrMissingPasswordArgs cr = new CorruptedRarOrMissingPasswordArgs(same, _AddRar);

                OnErrorUserExit(iel, cr);

                while ((!valid) && (cr.accept == true))
                {                      
                    Sex = new SevenZipExtractor(FileName, cr.Password);

                    valid = Sex.Check();
                    if (valid == false)
                    {
                        Sex.Dispose();
                        cr = new CorruptedRarOrMissingPasswordArgs(same, cr.SavePassword);

                        OnErrorUserExit(iel, cr);
                    } 
                }

                if (valid == false)
                    return null;
               
            }

            return Sex;
        }
    private void DoCheck() {
      string FileName = _ShellListView.GetFirstSelectedItem().ParsingName;
      var extractor = new SevenZipExtractor(FileName);
      if (!extractor.Check())
        MessageBox.Show("Not Pass");
      else
        MessageBox.Show("Pass");

      extractor.Dispose();
    }
        private void DoCheck()
        {

            SevenZipExtractor extractor = new SevenZipExtractor(archive.ParsingName);
            if (!extractor.Check())
                MessageBox.Show("Not Pass");
            else
                MessageBox.Show("Pass");

            extractor.Dispose();
        }
 private void btn_checkarchive_Click(object sender, EventArgs e)
 {
     var sevenZipExtractor = new SevenZipExtractor(_pathArchive);
     var check = sevenZipExtractor.Check();
     
     var dialog = new TaskDialog();
     dialog.Text = check ? CHECK_OKE : CHECK_ERROR;
     dialog.StandardButtons = TaskDialogStandardButtons.Ok;
     
     dialog.Show();
 }
        /// <summary>
        /// Compress All Folders in a path each folder to a individual 7zip file
        /// </summary>
        /// <param name="blShuttingDown"></param>
        private void compressFolder(ref bool blShuttingDown)
        {
            SevenZip.SevenZipCompressor compressor = null;
            SevenZip.SevenZipExtractor extractor = null;
            Stream exreader = null;
            Stream creader = null;
            Stream extestreader = null;

            string[] strfilearr = new string[1];

            try
            {
                SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder());
                string[] Directories = Directory.GetDirectories(SourceFolder);

                //Loop through every local directory
                foreach (string strDir in Directories)
                {
                    bool blArchiveOk = false;

                    DirectoryInfo DirInfo1 = new DirectoryInfo(strDir);
                    string str7Dir = Common.WindowsPathClean(DirInfo1.FullName + ".7z");
                    string strDestination = Common.WindowsPathCombine(DestinationFolder, str7Dir, SourceFolder);

                    if (blShuttingDown)
                    {
                        _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + strDir, System.Diagnostics.EventLogEntryType.Information, 5130, 50);
                        return;
                    }

                    if (!startCompressing(DirInfo1.LastWriteTime))
                    {
                        continue;
                    }

                    //Check for Original Folder
                    try
                    {
                        if (File.Exists(strDestination))
                        {
                            FileInfo file7 = new FileInfo(strDestination);
                            extestreader = new FileStream(strDestination, FileMode.Open);
                            extractor = new SevenZipExtractor(extestreader);

                            //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original
                            if (extractor.Check() && KeepOriginalFile == false)
                            {
                                //Same File compressed then ok to delete
                                if (DirInfo1.LastWriteTime == file7.LastWriteTime && Common.CalculateFolderSize(DirInfo1.FullName) == extractor.UnpackedSize && Common.GetFolderFileCount(DirInfo1.FullName) == extractor.FilesCount)
                                {
                                    Directory.Delete(DirInfo1.FullName, true);
                                }

                            }

                            continue;
                        }
                    }
                    catch (Exception)
                    {
                        _evt.WriteEntry("Compress: Failed to Delete Original File: " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                        continue;

                    }
                    finally
                    {
                        if (extestreader != null)
                        {
                            extestreader.Close();
                            extestreader.Dispose();
                            extestreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                    }

                    //Compression of Entire Folder
                    strfilearr[0] = DirInfo1.FullName;

                    try
                    {
                        compressor = new SevenZip.SevenZipCompressor();
                        compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
                        compressor.CompressionLevel = CompressionLvl;
                        compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {
                            compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256;

                        }

                        long lFreeSpace = 0;

                        lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder);

                        //Check for Enough Free Space to compress the file
                        if (((Common.CalculateFolderSize(SourceFolder) * 2.0f) > (float)lFreeSpace) && (lFreeSpace != -1))
                        {
                            _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                            compressor = null;
                            continue;

                        }

                        if (lFreeSpace == -1)
                        {
                            _evt.WriteEntry("Compress: Only files local to this machine should be compressed.  Performance problem can occur with large files over the network. " + DirInfo1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50);
                        }

                        //Compress or Compress and Encrypt Files
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {
                            //Compress and Encrypt the Folder if password is specified
                            creader = new FileStream(str7Dir, FileMode.OpenOrCreate);

                            AES256 aes = new AES256(ep);
                            string upassword = aes.Decrypt(_encryptionPassword);
                            compressor.CompressDirectory(DirInfo1.FullName, creader, upassword);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7Dir, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader, upassword);
                            upassword = "";
                        }
                        else
                        {
                            //Compress the Folder Normally
                            creader = new FileStream(str7Dir, FileMode.OpenOrCreate);

                            compressor.CompressDirectory(DirInfo1.FullName, creader);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7Dir, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader);

                        }

                        //7Zip file ok?
                        blArchiveOk = extractor.Check();
                        //close the archive so it can be deleted later
                        exreader.Close();
                        exreader.Dispose();
                        exreader = null;
                        verifyArchive(blArchiveOk, str7Dir, DirInfo1.FullName);

                    }
                    catch (Exception ex)
                    {
                        _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50);
                    }
                    finally
                    {
                        if (creader != null)
                        {
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                        }
                        if (exreader != null)
                        {
                            exreader.Close();
                            exreader.Dispose();
                            exreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                        compressor = null;
                    }

                }// end foreach
                _evt.WriteEntry("Compress: Compress Folders Completed", System.Diagnostics.EventLogEntryType.Information, 5000, 50);
            }
            catch (Exception ex)
            {
                _evt.WriteEntry("Compress: Compress Folders Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50);
            }
            finally
            {
                if (creader != null)
                {
                    creader.Close();
                    creader.Dispose();
                    creader = null;
                }
                if (exreader != null)
                {
                    exreader.Close();
                    exreader.Dispose();
                    exreader = null;
                }
                if (extractor != null)
                {
                    extractor.Dispose();
                    extractor = null;
                }
                if (extestreader != null)
                {
                    extestreader.Close();
                    extestreader.Dispose();
                    extestreader = null;
                }
                compressor = null;
            }
        }
        /// <summary>
        /// Compress files individually with .7z added on the end of the filename
        /// </summary>
        /// <param name="blShuttingDown"></param>
        private void compressFile(ref bool blShuttingDown)
        {
            SevenZip.SevenZipCompressor compressor = null;
            SevenZip.SevenZipExtractor extractor = null;
            Stream exreader = null;
            Stream creader = null;
            Stream extestreader = null;
            string[] strfilearr = new string[1];

            try
            {
                AllFiles = Common.WalkDirectory(SourceFolder, ref blShuttingDown, FileNameFilter);
                SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder());
                if (SourceFolder != DestinationFolder)
                {
                    Common.CreateDestinationFolders(SourceFolder, DestinationFolder);
                }
                if (blShuttingDown)
                {
                    throw new Exception("Shutting Down");
                }
                //Loop through every file
                foreach (System.IO.FileInfo file1 in AllFiles)
                {
                    string str7File = Common.WindowsPathClean(file1.FullName + ".7z");
                    string strDestination = Common.WindowsPathCombine(DestinationFolder, str7File, SourceFolder);

                    bool blArchiveOk = false;

                    if (blShuttingDown)
                    {
                        _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + file1.FullName, System.Diagnostics.EventLogEntryType.Information, 5130, 50);
                        throw new Exception("Shutting Down");
                    }

                    //Skip over already compressed files
                    if (file1.Extension.ToLower() == ".7z" || file1.Extension.ToLower() == ".zip" || file1.Extension.ToLower() == ".rar")
                    {
                        continue;
                    }

                    if (Common.IsFileLocked(file1))
                    {
                        _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5130, 50);
                        continue;
                    }

                    if (!startCompressing(file1.LastWriteTime))
                    {
                        continue;
                    }

                    try
                    {

                        if (File.Exists(strDestination))
                        {
                            extestreader = new FileStream(strDestination, FileMode.Open);
                            extractor = new SevenZipExtractor(extestreader);

                            //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original
                            if (extractor.Check() && KeepOriginalFile == false)
                            {

                                FileInfo file2 = new FileInfo(strDestination);
                                //Same File compressed then ok to delete
                                if (file1.LastWriteTime == file2.LastWriteTime && file1.Length == extractor.UnpackedSize && extractor.FilesCount == 1)
                                {
                                    //File.SetAttributes(file1.FullName, FileAttributes.Normal);
                                    file1.IsReadOnly = false;
                                    File.Delete(file1.FullName);
                                }
                                file2 = null;
                            }

                            continue;
                        }
                    }
                    catch (Exception)
                    {
                        _evt.WriteEntry("Compress: Failed to Delete Original File: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                        continue;

                    }
                    finally
                    {
                        if (extestreader != null)
                        {
                            extestreader.Close();
                            extestreader.Dispose();
                            extestreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                    }
                    //If file already zipped and the last modified time are the same then delete

                    //Compression of individual files
                    strfilearr[0] = file1.FullName;

                    try
                    {
                        compressor = new SevenZip.SevenZipCompressor();
                        compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
                        compressor.CompressionLevel = CompressionLvl;
                        compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {
                            compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256;

                        }

                        long lFreeSpace = 0;

                        lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder);

                        //Check for Enough Free Space to compress the file
                        if (((file1.Length * 2) > lFreeSpace) && (lFreeSpace != -1))
                        {
                            _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50);
                            compressor = null;
                            continue;

                        }

                        if (lFreeSpace == -1)
                        {
                            _evt.WriteEntry("Compress: Only files local to this machine should be compressed.  Performance problem can occur with large files over the network. " + file1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50);
                        }

                        //Compress or Compress and Encrypt Files
                        if (!string.IsNullOrEmpty(_encryptionPassword))
                        {

                            creader = new FileStream(str7File, FileMode.OpenOrCreate);

                            //Encrypt the file if password is specified
                            AES256 aes = new AES256(ep);
                            string upassword = aes.Decrypt(_encryptionPassword);
                            compressor.CompressFilesEncrypted(creader, upassword, strfilearr);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7File, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader, upassword);
                            upassword = "";
                        }
                        else
                        {
                            if (Common.IsFileLocked(file1))
                            {
                                _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5070, 50);
                                continue;
                            }
                            creader = new FileStream(str7File, FileMode.OpenOrCreate);

                            compressor.CompressFiles(creader, strfilearr);
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                            exreader = new FileStream(str7File, FileMode.Open);
                            extractor = new SevenZipExtractor(exreader);

                        }

                        //7Zip file ok?
                        blArchiveOk = extractor.Check();
                        exreader.Close();
                        exreader.Dispose();
                        exreader = null;
                        verifyArchive(blArchiveOk, str7File, file1.FullName);

                    }
                    catch (Exception ex)
                    {
                        _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50);
                    }
                    finally
                    {
                        if (creader != null)
                        {
                            creader.Close();
                            creader.Dispose();
                            creader = null;
                        }
                        if (exreader != null)
                        {
                            exreader.Close();
                            exreader.Dispose();
                            exreader = null;
                        }
                        if (extractor != null)
                        {
                            extractor.Dispose();
                            extractor = null;
                        }
                        compressor = null;
                    }

                }// end foreach
                _evt.WriteEntry("Compress: Complete Files Compressed: " + FilesCompressed.Count, System.Diagnostics.EventLogEntryType.Information, 5000, 50);
            }
            catch (Exception ex)
            {
                _evt.WriteEntry("Compress: Compress Files Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50);
            }
            finally
            {
                if (creader != null)
                {
                    creader.Close();
                    creader.Dispose();
                    creader = null;
                }
                if (exreader != null)
                {
                    exreader.Close();
                    exreader.Dispose();
                    exreader = null;
                }
                if (extractor != null)
                {
                    extractor.Dispose();
                    extractor = null;
                }
                if (extestreader != null)
                {
                    extestreader.Close();
                    extestreader.Dispose();
                    extestreader = null;
                }
                compressor = null;
            }
        }