Exemple #1
0
 private bool GuessFormatFromSignature(string filePath, out SevenZipFormat format)
 {
     using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         return(GuessFormatFromSignature(fileStream, out format));
     }
 }
Exemple #2
0
        private bool GuessFormatFromExtension(string fileExtension, out SevenZipFormat format)
        {
            if (string.IsNullOrWhiteSpace(fileExtension))
            {
                format = SevenZipFormat.Undefined;
                return(false);
            }

            fileExtension = fileExtension.TrimStart('.').Trim().ToLowerInvariant();

            if (fileExtension.Equals("rar"))
            {
                // 7z has different GUID for Pre-RAR5 and RAR5, but they have both same extension (.rar)
                // If it is [0x52 0x61 0x72 0x21 0x1A 0x07 0x01 0x00] then file is RAR5 otherwise RAR.
                // https://www.rarlab.com/technote.htm

                // We are unable to guess right format just by looking at extension and have to check signature

                format = SevenZipFormat.Undefined;
                return(false);
            }

            if (!Formats.ExtensionFormatMapping.ContainsKey(fileExtension))
            {
                format = SevenZipFormat.Undefined;
                return(false);
            }

            format = Formats.ExtensionFormatMapping[fileExtension];
            return(true);
        }
        public ArchiveFile(string archiveFilePath, string libraryFilePath = null)
        {
            this.libraryFilePath = libraryFilePath;

            this.InitializeAndValidateLibrary();

            if (!File.Exists(archiveFilePath))
            {
                throw new SevenZipException("Archive file not found");
            }

            string extension = Path.GetExtension(archiveFilePath);

            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new SevenZipException("Unable to guess format for file: " + archiveFilePath);
            }

            string fileExtension = extension.Trim('.').ToLowerInvariant();

            if (!Formats.ExtensionFormatMapping.ContainsKey(fileExtension))
            {
                throw new SevenZipException(fileExtension + " is not a known archive type");
            }

            SevenZipFormat format = this.GuessFormatFromExtension(archiveFilePath, fileExtension);

            this.archive       = this.sevenZipHandle.CreateInArchive(Formats.FormatGuidMapping[format]);
            this.archiveStream = new InStreamWrapper(File.OpenRead(archiveFilePath));
        }
Exemple #4
0
        private bool GuessFormatFromSignature(Stream stream, out SevenZipFormat format)
        {
            int longestSignature = Formats.FileSignatures.Values.OrderByDescending(v => v.Length).First().Length;

            byte[] archiveFileSignature = new byte[longestSignature];
            int    bytesRead            = stream.Read(archiveFileSignature, 0, longestSignature);

            stream.Position -= bytesRead; // go back o beginning

            if (bytesRead != longestSignature)
            {
                format = SevenZipFormat.Undefined;
                return(false);
            }

            foreach (KeyValuePair <SevenZipFormat, byte[]> pair in Formats.FileSignatures)
            {
                if (archiveFileSignature.Take(pair.Value.Length).SequenceEqual(pair.Value))
                {
                    format = pair.Key;
                    return(true);
                }
            }

            format = SevenZipFormat.Undefined;
            return(false);
        }
Exemple #5
0
        public static bool GuessFormatFromSignature(Stream stream, out SevenZipFormat format)
        {
            FileSignature longestSig          = FileSignatures.Values.OrderByDescending(v => v.Magic.Length + v.Offset).First();
            int           longestSignatureLen = longestSig.Magic.Length + longestSig.Offset;

            byte[] archiveFileSignature = new byte[longestSignatureLen];
            int    bytesRead            = stream.Read(archiveFileSignature, 0, longestSignatureLen);

            stream.Position -= bytesRead; // go back o beginning

            if (bytesRead != longestSignatureLen)
            {
                format = SevenZipFormat.Undefined;
                return(false);
            }

            foreach (KeyValuePair <SevenZipFormat, FileSignature> pair in FileSignatures)
            {
                if (archiveFileSignature.Skip(pair.Value.Offset).Take(pair.Value.Magic.Length).SequenceEqual(pair.Value.Magic))
                {
                    format = pair.Key;
                    return(true);
                }
            }

            format = SevenZipFormat.Undefined;
            return(false);
        }
Exemple #6
0
        public static SevenZipFormat?FindSevenZipFormat(this string fileExtension, Stream data, SevenZipFormat?fallback = null)
        {
            data.Seek(0, SeekOrigin.Begin);
            SevenZipFormat szf = new SevenZipFormat();

            if (GuessFormatFromSignature(data, out szf))
            {
                return(szf);
            }
            return(fallback);
        }
Exemple #7
0
        public string Extract(string archiveName, string folderToExtract, uint fileNumber, KnownSevenZipFormat ZipFormat, out bool isDirectory)
        {
            isDirectory = false;

            ZipFormatG = ZipFormat;

            string FileName = null;

            try
            {
                using (SevenZipFormat Format = new SevenZipFormat(SevenZipDllPath))
                {
                    IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(ZipFormat));
                    if (Archive == null)
                    {
                        return(null);
                    }

                    try
                    {
                        using (InStreamWrapper ArchiveStream = new InStreamWrapper(File.OpenRead(archiveName)))
                        {
                            IArchiveOpenCallback OpenCallback = new ArchiveOpenCallback();

                            ulong CheckPos = 256 * 1024;

                            if (Archive.Open(ArchiveStream, ref CheckPos, OpenCallback) != 0)
                            {
                                return(null);
                            }

                            PropVariant Name = new PropVariant();
                            Archive.GetProperty(fileNumber, ItemPropId.kpidPath, ref Name);
                            FileName = (string)Name.GetObject();
                            Archive.GetProperty(fileNumber, ItemPropId.kpidIsFolder, ref Name);
                            isDirectory = (bool)Name.GetObject();

                            if (!isDirectory)
                            {
                                Archive.Extract(new uint[] { fileNumber }, 1, 0, new ArchiveExtractCallback(fileNumber, folderToExtract + FileName));
                            }
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(Archive);
                    }
                }
            }
            catch
            {
            }
            return(FileName);
        }
Exemple #8
0
        private static void ListOrExtract(string archiveName, string extractLocation, bool extract)
        {
            using (SevenZipFormat Format = new SevenZipFormat(SevenZDllPath)) {
                IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.SevenZip));
                if (Archive == null)
                {
                    return;
                }

                try {
                    using (InStreamWrapper ArchiveStream = new InStreamWrapper(File.OpenRead(archiveName))) {
                        IArchiveOpenCallback OpenCallback = new ArchiveOpenCallback();

                        // 32k CheckPos is not enough for some 7z archive formats
                        ulong CheckPos = 128 * 1024;
                        if (Archive.Open(ArchiveStream, ref CheckPos, OpenCallback) != 0)
                        {
                            return;
                        }

                        if (extract)
                        {
                            uint Count = Archive.GetNumberOfItems();
                            for (int i = 0; i < Count; i++)
                            {
                                PropVariant Name = new PropVariant();
                                Archive.GetProperty((uint)i, ItemPropId.kpidPath, ref Name);
                                string FileName = (string)Name.GetObject();
                                Archive.Extract(new uint[] { (uint)i }, 1, 0, new ArchiveExtractCallback((uint)i, FileName, extractLocation));
                            }
                        }
                        else
                        {
                            //Console.WriteLine("List:");
                            String files = "";
                            uint   Count = Archive.GetNumberOfItems();
                            for (uint I = 0; I < Count; I++)
                            {
                                PropVariant Name = new PropVariant();
                                Archive.GetProperty(I, ItemPropId.kpidPath, ref Name);
                                files += String.Format("{0} - {1}\r\n", I, Name.GetObject());
                            }
                            MessageBox.Show(files);
                        }
                    }
                } finally {
                    Marshal.ReleaseComObject(Archive);
                }
            }
        }
        public ArchiveFile(Stream archiveStream, SevenZipFormat format, string libraryFilePath = null)
        {
            this.libraryFilePath = libraryFilePath;

            this.InitializeAndValidateLibrary();

            if (archiveStream == null)
            {
                throw new SevenZipException("archiveStream is null");
            }

            this.archive       = this.sevenZipHandle.CreateInArchive(Formats.FormatGuidMapping[format]);
            this.archiveStream = new InStreamWrapper(archiveStream);
        }
Exemple #10
0
 static SevenZipExtractor()
 {
     if (IntPtr.Size == 4)
     {
         format = new SevenZipFormat(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "x86", "7z.dll"));
     }
     else if (IntPtr.Size == 8)
     {
         format = new SevenZipFormat(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "x64", "7z.dll"));
     }
     else
     {
         throw new PlatformNotSupportedException();
     }
 }
        public FirebirdDataAccess(TCommonFireBirdDB manager)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            this.manager = manager;
            this.connection = manager.Connection;

            XsltSettings settings = new XsltSettings();

            this.xslt = new XslCompiledTransform();
            this.xslt.Load("fb2_text_annotation.xsl", settings, new XmlResourceResolver());
            format = new SevenZipFormat("other/7z.dll");
        }
Exemple #12
0
        public List <string> List(string archiveName, KnownSevenZipFormat ZipFormat)
        {
            List <string> List = new List <string>();

            using (SevenZipFormat Format = new SevenZipFormat(SevenZipDllPath))
            {
                IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(ZipFormat));
                if (Archive == null)
                {
                    return(List);
                }

                try
                {
                    using (InStreamWrapper ArchiveStream = new InStreamWrapper(File.OpenRead(archiveName)))
                    {
                        IArchiveOpenCallback OpenCallback = new ArchiveOpenCallback();

                        ulong CheckPos = 256 * 1024;

                        if (Archive.Open(ArchiveStream, ref CheckPos, OpenCallback) != 0)
                        {
                            return(List);
                        }

                        uint Count = Archive.GetNumberOfItems();
                        for (uint I = 0; I < Count; I++)
                        {
                            PropVariant Name = new PropVariant();
                            Archive.GetProperty(I, ItemPropId.kpidPath, ref Name);
                            string[] T = Name.GetObject().ToString().Split('\\');
                            List.Add(T[T.Length - 1]);
                        }
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(Archive);
                }
            }

            return(List);
        }
        public override FileFormat Match(FileFormatScanJob job)
        {
            if (FileFormatUtils.IsNullOrEmpty(job.StartBytes))
            {
                return(null);
            }

            if (job.StartBytes.Length <= Signature.Length)
            {
                return(null);
            }

            if (!FileFormatUtils.MatchBytes(job.StartBytes, Signature))
            {
                return(null);
            }

            var fingerprint = new SevenZipFormat();

            return(fingerprint);
        }
Exemple #14
0
        public IDisposable Subscribe(IObserver <SevenZipArchiveFile> observer)
        {
            var subject = new Subject <SevenZipArchiveFile>();

            subject.Subscribe(observer);
            var archive = format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.SevenZip));

            try
            {
                using (var fileStream = File.OpenRead(this.Name))
                {
                    var maxCheckStartPosition = 128UL * 1024UL;
                    if (archive.Open(new InStreamWrapper(fileStream), ref maxCheckStartPosition, new ArchiveOpenCallback()) != 0)
                    {
                        throw new IOException();
                    }
                    var indices = Enumerable.Range(0, (int)archive.GetNumberOfItems())
                                  .Select(index => (uint)index)
                                  .Where(index =>
                    {
                        var value = new PropVariant();
                        archive.GetProperty(index, ItemPropId.kpidIsFolder, ref value);
                        return(!(bool)value.GetObject());
                    })
                                  .ToArray();
                    using (var callback = new ArchiveExtractCallback(archive))
                    {
                        callback.Subscribe(subject);
                        archive.Extract(indices, (uint)indices.Length, 0, callback);
                    }
                }
                subject.OnCompleted();
                return(subject);
            }
            finally
            {
                Marshal.ReleaseComObject(archive);
            }
        }
Exemple #15
0
 /// <summary>
 /// Method to try opening an archive, based on an archive type
 /// </summary>
 /// <param name="stream">Memory stream of the archive</param>
 /// <param name="format">Predefined archive format</param>
 /// <param name="archive">Opened archive as out parameter. May be null in case of an error</param>
 /// <param name="error">Error message. May be empty, if no error occurred</param>
 /// <returns>True if the extraction was successful, otherwise false</returns>
 private static bool OpenArchive(ref MemoryStream stream, SevenZipFormat format, out ArchiveFile archive, out string error)
 {
     try
     {
         archive = new ArchiveFile(stream, format);
         if (archive.Entries.Count != 0)
         {
             error = string.Empty;
             return(true);
         }
         else // will be triggered when the archive is valid but empty
         {
             error = "Empty Archive";
             return(false);
         }
     }
     catch (Exception ex)
     {
         archive         = null;
         stream.Position = 0;
         error           = ex.Message;
         return(false);
     }
 }
Exemple #16
0
 private string ExtractFile(string fileName)
 {
     if (isMono)
         return fileName;
     SystemState old = state;
     state = SystemState.SystemPause;
     string ext = Path.GetExtension(fileName).ToLower();
     if (ext == ".7z" || ext == ".zip" || ext == ".rar")
     {
         string sevenZ = this.config["7z"];
         if (IntPtr.Size == 8)
             sevenZ = this.config["7z64"]; //replace this with installer logic maybe?
         SevenZipFormat Format = new SevenZipFormat(sevenZ);
         KnownSevenZipFormat fileType;
         switch (ext)
         {
             default:
             case ".7z":
                 fileType = KnownSevenZipFormat.SevenZip;
                 break;
             case ".zip":
                 fileType = KnownSevenZipFormat.Zip;
                 break;
             case ".rar":
                 fileType = KnownSevenZipFormat.Rar;
                 break;
         }
         IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(fileType));
         try
         {
             InStreamWrapper ArchiveStream = new InStreamWrapper(File.OpenRead(fileName));
             ulong checkPos = 32 * 1024;
             Archive.Open(ArchiveStream, ref checkPos, null);
             uint count = Archive.GetNumberOfItems();
             string[] archiveContent = new string[count];
             for (uint i = 0; i < count; i++)
             {
                 PropVariant name = new PropVariant();
                 Archive.GetProperty(i, ItemPropId.kpidPath, ref name);
                 archiveContent[i] = name.GetObject().ToString();
             }
             if (count == 1)
             {
                 fileName = Path.Combine(this.config["tmpDir"], Path.GetFileNameWithoutExtension(archiveContent[0]) + ".tmp" + Path.GetExtension(archiveContent[0]));
                 Archive.Extract(new uint[] { 0 }, 1, 0, new ArchiveCallback(0, fileName));
             }
             else
             {
                 ArchiveViewer viewer = new ArchiveViewer(archiveContent);
                 if (viewer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                 {
                     fileName = Path.Combine(this.config["tmpDir"], Path.GetFileNameWithoutExtension(archiveContent[viewer.selectedFile]) + ".tmp" + Path.GetExtension(archiveContent[0]));
                     Archive.Extract(new uint[] { (uint)viewer.selectedFile }, 1, 0, new ArchiveCallback((uint)viewer.selectedFile, fileName));
                 }
                 else
                 {
                     fileName = "";
                 }
             }
             ArchiveStream.Dispose();
         }
         finally
         {
             Archive.Close();
             Marshal.ReleaseComObject(Archive);
         }
         Format.Dispose();
     }
     state = old;
     return fileName;
 }
 public SevenZipFileProvider()
 {
     sevenZip = new SevenZipFormat(@"other\7z.dll");
     defaultListeners = new List<IFileSystemListener>();
 }