示例#1
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);
        }
示例#2
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);
                }
            }
        }
示例#3
0
 static int CountFilesInArchive(string arcName)
 {
     arhContent = new List <string>();
     using (SevenZipFormat Format = new SevenZipFormat(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll")))
     {
         IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.Arj));
         if (Archive == null)
         {
             return(0);
         }
         try
         {
             using (InStreamWrapper ArchiveStream = new InStreamWrapper(File.OpenRead(arcName)))
             {
                 ulong checkPos = 32 * 1024;
                 if (Archive.Open(ArchiveStream, ref checkPos, null) != 0)
                 {
                     Console.WriteLine("Error!!!");
                 }
                 uint Count = Archive.GetNumberOfItems();
                 for (uint i = 0; i < Count; i++)
                 {
                     PropVariant Name = new PropVariant();
                     Archive.GetProperty(i, ItemPropId.kpidPath, ref Name);
                     arhContent.Add(Name.GetObject().ToString());
                 }
             }
         }
         finally
         {
             Marshal.ReleaseComObject(Archive);
         }
     }
     return(arhContent.Count);
 }
        /* ----------------------------------------------------------------- */
        ///
        /// Get
        ///
        /// <summary>
        /// Gets information corresponding to the specified ID.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public static T Get <T>(this IInArchive src, int index, ItemPropId pid)
        {
            var var = new PropVariant();

            src.GetProperty((uint)index, pid, ref var);

            var obj = var.Object;

            return(obj is T dest ? dest : default);
示例#5
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);
        }
        /// <summary>
        /// Sets output stream for writing unpacked data
        /// </summary>
        /// <param name="index">Current file index</param>
        /// <param name="outStream">Output stream pointer</param>
        /// <param name="askExtractMode">Extraction mode</param>
        /// <returns>0 if OK</returns>
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            outStream = null;

            if (Canceled)
            {
                return(-1);
            }
            _currentIndex = (int)index;
            if (askExtractMode == AskMode.Extract)
            {
                var fileName = _directory;
                if (!_fileIndex.HasValue)
                {
                    #region Extraction to a file

                    if (_actualIndexes == null || _actualIndexes.Contains(index))
                    {
                        var data = new PropVariant();
                        _archive.GetProperty(index, ItemPropId.Path, ref data);
                        string entryName = NativeMethods.SafeCast(data, "");

                        #region Get entryName

                        if (String.IsNullOrEmpty(entryName))
                        {
                            if (_filesCount == 1)
                            {
                                var archName = Path.GetFileName(_extractor.FileName);
                                archName = archName.Substring(0, archName.LastIndexOf('.'));
                                if (!archName.EndsWith(".tar", StringComparison.OrdinalIgnoreCase))
                                {
                                    archName += ".tar";
                                }
                                entryName = archName;
                            }
                            else
                            {
                                entryName = "[no name] " + index.ToString(CultureInfo.InvariantCulture);
                            }
                        }

                        #endregion

                        try
                        {
                            fileName = Path.Combine(RemoveIllegalCharacters(_directory, true), RemoveIllegalCharacters(_directoryStructure ? entryName : Path.GetFileName(entryName)));
                            ValidateFileNameAndCreateDirectory(fileName);
                        }
                        catch (Exception e)
                        {
                            AddException(e);
                            goto FileExtractionStartedLabel;
                        }

                        _archive.GetProperty(index, ItemPropId.IsDirectory, ref data);
                        if (!NativeMethods.SafeCast(data, false))
                        {
                            #region Branch

                            _archive.GetProperty(index, ItemPropId.LastWriteTime, ref data);
                            var time = NativeMethods.SafeCast(data, DateTime.MinValue);
                            if (File.Exists(fileName))
                            {
                                var fnea = new FileOverwriteEventArgs(fileName);
                                OnFileExists(fnea);
                                if (fnea.Cancel)
                                {
                                    Canceled = true;
                                    return(-1);
                                }
                                if (String.IsNullOrEmpty(fnea.FileName))
                                {
                                    outStream = _fakeStream;

                                    goto FileExtractionStartedLabel;
                                }
                                fileName = fnea.FileName;
                            }
                            try
                            {
                                _fileStream = new OutStreamWrapper(File.Create(fileName), fileName, time, true);
                            }
                            catch (Exception e)
                            {
                                if (e is FileNotFoundException)
                                {
                                    AddException(
                                        new IOException("The file \"" + fileName +
                                                        "\" was not extracted due to the File.Create fail."));
                                }
                                else
                                {
                                    AddException(e);
                                }
                                outStream = _fakeStream;
                                goto FileExtractionStartedLabel;
                            }
                            _fileStream.BytesWritten += IntEventArgsHandler;
                            outStream = _fileStream;

                            #endregion
                        }
                        else
                        {
                            #region Branch

                            if (!Directory.Exists(fileName))
                            {
                                try
                                {
                                    Directory.CreateDirectory(fileName);
                                }
                                catch (Exception e)
                                {
                                    AddException(e);
                                }
                                outStream = _fakeStream;
                            }

                            #endregion
                        }
                    }
                    else
                    {
                        outStream = _fakeStream;
                    }

                    #endregion
                }
                else
                {
                    #region Extraction to a stream

                    if (index == _fileIndex)
                    {
                        outStream  = _fileStream;
                        _fileIndex = null;
                    }
                    else
                    {
                        outStream = _fakeStream;
                    }

                    #endregion
                }

FileExtractionStartedLabel:
                _doneRate += 1.0f / _filesCount;
                var iea = new FileInfoEventArgs(
                    _extractor.ArchiveFileData[(int)index], PercentDoneEventArgs.ProducePercentDone(_doneRate));
                OnFileExtractionStarted(iea);
                if (iea.Cancel)
                {
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        _fileStream.Dispose();
                        if (File.Exists(fileName))
                        {
                            try
                            {
                                File.Delete(fileName);
                            }
                            catch (Exception e)
                            {
                                AddException(e);
                            }
                        }
                    }
                    Canceled = true;
                    return(-1);
                }
            }
            return(0);
        }
示例#7
0
 internal Variant(IInArchive Archive, uint FileNumber, ItemPropId Id)
 {
     Archive.GetProperty(FileNumber, Id, ref variant);
 }
示例#8
0
        public int findFirstExtInArchive(string ext, string archiveName, string arcType, ProgressBar progress, Label status)
        {
            status.Text      = "Scanning Archive " + archiveName;
            progress.Maximum = 4;
            progress.Value   = 0;
            Application.DoEvents();
            int num = -1;

            using (SevenZipFormat format = new SevenZipFormat(SevenZipDllPath))
            {
                KnownSevenZipFormat sevenZip = KnownSevenZipFormat.SevenZip;
                arcType = arcType.ToLower();
                switch (arcType)
                {
                case "rar":
                    sevenZip = KnownSevenZipFormat.Rar;
                    break;

                case "zip":
                    sevenZip = KnownSevenZipFormat.Zip;
                    break;

                case "7z":
                    sevenZip = KnownSevenZipFormat.SevenZip;
                    break;

                default:
                    showError("0.1");
                    break;
                }
                IInArchive o = format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(sevenZip));
                if (o == null)
                {
                    showError("0.2");
                    num = -1;
                }
                try
                {
                    using (InStreamWrapper wrapper = new InStreamWrapper(System.IO.File.OpenRead(archiveName)))
                    {
                        IArchiveOpenCallback openArchiveCallback = new ArchiveOpenCallback();
                        if (o.Open(wrapper, 0x40000L, openArchiveCallback) != 0)
                        {
                            showError("0.3");
                            num = -1;
                        }
                        uint numberOfItems = o.GetNumberOfItems();
                        fileInRar = "";
                        for (int i = 0; i < numberOfItems; i++)
                        {
                            PropVariant variant = new PropVariant();
                            o.GetProperty((uint)i, ItemPropId.kpidPath, ref variant);
                            PropVariant variant2 = new PropVariant();
                            o.GetProperty((uint)i, ItemPropId.kpidCRC, ref variant2);
                            if (Program.form.getFileExtension(variant.GetObject().ToString()).ToLower() == ext.ToLower())
                            {
                                num       = i;
                                fileInRar = variant.GetObject().ToString();
                                this.crc_of_extracting_file = long.Parse(variant2.GetObject().ToString()).ToString("X8");
                                return(num);
                            }
                        }
                        return(num);
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(o);
                }
            }
            return(num);
        }
示例#9
0
 internal Variant(IInArchive Archive, uint FileNumber, ItemPropId Id)
 {
     Archive.GetProperty(FileNumber, Id, ref variant);
 }
        /// <summary>
        /// Retrieves all information about the archive.
        /// </summary>
        /// <exception cref="SevenZip.SevenZipArchiveException"/>
        private void GetArchiveInfo(bool disposeStream)
        {
            if (_archive == null)
            {
                if (!ThrowException(null, new SevenZipArchiveException()))
                {
                    return;
                }
            }
            else
            {
                IInStream archiveStream;
                using ((archiveStream = GetArchiveStream(disposeStream)) as IDisposable)
                {
                    var openCallback = GetArchiveOpenCallback();
                    if (!_opened)
                    {
                        if (!OpenArchive(archiveStream, openCallback))
                        {
                            return;
                        }
                        _opened = !disposeStream;
                    }
                    _filesCount      = _archive.GetNumberOfItems();
                    _archiveFileData = new List <ArchiveFileInfo>((int)_filesCount);
                    if (_filesCount != 0)
                    {
                        var data = new PropVariant();
                        try
                        {
                            #region Getting archive items data

                            for (uint i = 0; i < _filesCount; i++)
                            {
                                try
                                {
                                    var fileInfo = new ArchiveFileInfo {
                                        Index = (int)i
                                    };
                                    _archive.GetProperty(i, ItemPropId.Path, ref data);
                                    fileInfo.FileName = NativeMethods.SafeCast(data, "[no name]");
                                    _archive.GetProperty(i, ItemPropId.LastWriteTime, ref data);
                                    fileInfo.LastWriteTime = NativeMethods.SafeCast(data, DateTime.Now);
                                    _archive.GetProperty(i, ItemPropId.CreationTime, ref data);
                                    fileInfo.CreationTime = NativeMethods.SafeCast(data, DateTime.Now);
                                    _archive.GetProperty(i, ItemPropId.LastAccessTime, ref data);
                                    fileInfo.LastAccessTime = NativeMethods.SafeCast(data, DateTime.Now);
                                    _archive.GetProperty(i, ItemPropId.Size, ref data);
                                    fileInfo.Size = NativeMethods.SafeCast <ulong>(data, 0);
                                    if (fileInfo.Size == 0)
                                    {
                                        fileInfo.Size = NativeMethods.SafeCast <uint>(data, 0);
                                    }
                                    _archive.GetProperty(i, ItemPropId.Attributes, ref data);
                                    fileInfo.Attributes = NativeMethods.SafeCast <uint>(data, 0);
                                    _archive.GetProperty(i, ItemPropId.IsDirectory, ref data);
                                    fileInfo.IsDirectory = NativeMethods.SafeCast(data, false);
                                    _archive.GetProperty(i, ItemPropId.Encrypted, ref data);
                                    fileInfo.Encrypted = NativeMethods.SafeCast(data, false);
                                    _archive.GetProperty(i, ItemPropId.Crc, ref data);
                                    fileInfo.Crc = NativeMethods.SafeCast <uint>(data, 0);
                                    _archive.GetProperty(i, ItemPropId.Comment, ref data);
                                    fileInfo.Comment = NativeMethods.SafeCast(data, "");
                                    _archive.GetProperty(i, ItemPropId.Method, ref data);
                                    fileInfo.Method = NativeMethods.SafeCast(data, "");
                                    _archiveFileData.Add(fileInfo);
                                }
                                catch (InvalidCastException)
                                {
                                    ThrowException(null, new SevenZipArchiveException("probably archive is corrupted."));
                                }
                            }

                            #endregion

                            #region Getting archive properties

                            uint numProps  = _archive.GetNumberOfArchiveProperties();
                            var  archProps = new List <ArchiveProperty>((int)numProps);
                            for (uint i = 0; i < numProps; i++)
                            {
                                _archive.GetArchivePropertyInfo(i, out string propName, out var propId, out var varType);
                                _archive.GetArchiveProperty(propId, ref data);

                                if (propId == ItemPropId.Solid)
                                {
                                    _isSolid = NativeMethods.SafeCast(data, true);
                                }

                                // TODO Add more archive properties
                                if (PropIdToName.PropIdNames.ContainsKey(propId))
                                {
                                    archProps.Add(new ArchiveProperty
                                    {
                                        Name  = PropIdToName.PropIdNames[propId],
                                        Value = data.Object
                                    });
                                }
                                else
                                {
                                    Debug.WriteLine($"An unknown archive property encountered (code {((int)propId).ToString(CultureInfo.InvariantCulture)})");
                                }
                            }

                            _archiveProperties = new ReadOnlyCollection <ArchiveProperty>(archProps);

                            if (!_isSolid.HasValue && _format == InArchiveFormat.Zip)
                            {
                                _isSolid = false;
                            }

                            if (!_isSolid.HasValue)
                            {
                                _isSolid = true;
                            }

                            #endregion
                        }
                        catch (Exception)
                        {
                            if (openCallback.ThrowException())
                            {
                                throw;
                            }
                        }
                    }
                }

                if (disposeStream)
                {
                    _archive.Close();
                    _archiveStream = null;
                }

                _archiveFileInfoCollection = new ReadOnlyCollection <ArchiveFileInfo>(_archiveFileData);
            }
        }
示例#11
0
 public void GetProperty(UInt32 index, ItemPropId propID, ref PropVariant value)
 {
     inArchive.GetProperty(index, propID, ref value);
 }