示例#1
0
        public static RARFileInfo[] GetFiles(string rarPath)
        {
            lock (_readLock)
            {
                List<RARFileInfo> rarFileInfoList = new List<RARFileInfo>();
                using (Unrar unrar = new Unrar())
                {
                    try
                    {
                        unrar.Open(rarPath, Unrar.OpenMode.List);

                        while (unrar.ReadHeader())
                        {
                            if (!unrar.CurrentFile.IsDirectory)
                                rarFileInfoList.Add(unrar.CurrentFile);
                            unrar.Skip();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    return rarFileInfoList.ToArray();
                }
            }
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rarArchive">rar文件地址</param>
        /// <param name="destinationPath">目标地址</param>
        /// <param name="CreateDir">是否创建目录</param>
        public static void DecompressRar(string rarArchive, string destinationPath, bool CreateDir)
        {
            if (File.Exists(rarArchive))
            {
                Unrar tmp = new Unrar(rarArchive);
                tmp.Open(Unrar.OpenMode.List);
                string[] files = tmp.ListFiles();
                tmp.Close();

                Unrar unrar = new Unrar(rarArchive);
                unrar.Open(Unrar.OpenMode.Extract);
                unrar.DestinationPath = destinationPath;

                while (unrar.ReadHeader())
                {
                    if (unrar.CurrentFile.IsDirectory)
                    {
                        unrar.Skip();
                    }
                    else
                    {
                        if (CreateDir)
                        {
                            unrar.Extract();
                        }
                        else
                        {
                            unrar.Extract(destinationPath + Path.GetFileName(unrar.CurrentFile.FileName));
                        }
                    }
                }
                unrar.Close();
            }
        }
示例#3
0
 public void Dispose()
 {
     if (this.archiveHandle != IntPtr.Zero)
     {
         Unrar.RARCloseArchive(this.archiveHandle);
         this.archiveHandle = IntPtr.Zero;
     }
 }
示例#4
0
        private void extractButton_Click(object sender, System.EventArgs e)
        {
            // Get hashtable of selected files
            Hashtable selectedFiles = GetSelectedFiles();

            try
            {
                // Get destination from user
                string directory = Path.GetDirectoryName(rarFileName.Text);
                if (Directory.Exists(directory))
                {
                    folderBrowser.SelectedPath = directory;
                }
                if (folderBrowser.ShowDialog() == DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;

                    // Create new unrar class and attach event handlers for
                    // progress, missing volumes, and password
                    unrar = new Unrar();
                    AttachHandlers(unrar);

                    // Set destination path for all files
                    unrar.DestinationPath = folderBrowser.SelectedPath;

                    // Open archive for extraction
                    unrar.Open(rarFileName.Text, Unrar.OpenMode.Extract);

                    // Extract each file found in hashtable
                    while (unrar.ReadHeader())
                    {
                        if (selectedFiles.ContainsKey(unrar.CurrentFile.FileName))
                        {
                            this.progressBar.Value = 0;
                            unrar.Extract();
                        }
                        else
                        {
                            unrar.Skip();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor            = Cursors.Default;
                this.statusBar.Text    = "Ready";
                this.progressBar.Value = 0;
                if (this.unrar != null)
                {
                    unrar.Close();
                }
            }
        }
示例#5
0
        private void Extract(string destinationPath, string destinationName)
        {
            int result = Unrar.RARProcessFile(this.archiveHandle, (int)Operation.Extract, destinationPath, destinationName);

            // Check result
            if (result != 0)
            {
                ProcessFileError(result);
            }
        }
示例#6
0
        /// <summary>
        /// Tests the ability to extract the current file without saving extracted data to disk
        /// </summary>
        /// <returns></returns>
        public void Test()
        {
            int result = Unrar.RARProcessFile(this.archiveHandle, (int)Operation.Test, string.Empty, string.Empty);

            // Check result
            if (result != 0)
            {
                ProcessFileError(result);
            }
        }
示例#7
0
        private void OpenRarFile(string fileName)
        {
            try
            {
                this.Cursor           = Cursors.WaitCursor;
                testButton.Enabled    = false;
                extractButton.Enabled = false;
                fileList.BeginUpdate();
                fileList.Items.Clear();

                // Create new unrar class and open archive for listing files
                unrar = new Unrar();
                unrar.Open(fileName, Unrar.OpenMode.List);

                // Read each header, skipping directory entries
                while (unrar.ReadHeader())
                {
                    if (!unrar.CurrentFile.IsDirectory)
                    {
                        ListViewItem item = new ListViewItem(unrar.CurrentFile.FileName);
                        item.SubItems.Add(unrar.CurrentFile.UnpackedSize.ToString());
                        item.SubItems.Add(unrar.CurrentFile.PackedSize.ToString());
                        item.SubItems.Add(unrar.CurrentFile.FileTime.ToString());
                        item.Checked = true;
                        fileList.Items.Add(item);
                    }
                    unrar.Skip();
                }

                // Cleanup and enable buttons if no exception was thrown
                unrar.Close();
                this.unrar            = null;
                testButton.Enabled    = true;
                extractButton.Enabled = true;
            }
            catch (Exception ex)
            {
                testButton.Enabled    = false;
                extractButton.Enabled = false;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                fileList.EndUpdate();
                if (this.unrar != null)
                {
                    unrar.Close();
                }
            }
        }
示例#8
0
        private void testButton_Click(object sender, System.EventArgs e)
        {
            // Get hashtable of selected files
            Hashtable selectedFiles = GetSelectedFiles();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Create new unrar class and attach event handlers for
                // progress, missing volumes, and password
                unrar = new Unrar();
                AttachHandlers(unrar);

                // Open archive for extraction
                unrar.Open(rarFileName.Text, Unrar.OpenMode.Extract);

                // Test each file found in hashtable
                while (unrar.ReadHeader())
                {
                    if (selectedFiles.ContainsKey(unrar.CurrentFile.FileName))
                    {
                        this.progressBar.Value = 0;
                        unrar.Test();
                    }
                    else
                    {
                        unrar.Skip();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor            = Cursors.Default;
                this.statusBar.Text    = "Ready";
                this.progressBar.Value = 0;
                if (this.unrar != null)
                {
                    unrar.Close();
                }
            }
        }
示例#9
0
        /// <summary>
        /// Close the currently open archive
        /// </summary>
        /// <returns></returns>
        public void Close()
        {
            // Exit without exception if no archive is open
            if (this.archiveHandle == IntPtr.Zero)
            {
                return;
            }

            // Close archive
            int result = Unrar.RARCloseArchive(this.archiveHandle);

            // Check result
            if (result != 0)
            {
                ProcessFileError(result);
            }
            else
            {
                this.archiveHandle = IntPtr.Zero;
            }
        }
示例#10
0
 public static byte[] GetBytes(string rarPath, string filePath)
 {
     lock (_readLock)
     {
         using (Unrar unrar = new Unrar())
         {
             try
             {
                 //Unrar file in temporary directory
                 string tempDir = System.IO.Path.Combine(Environment.CurrentDirectory, "Temp");
                 unrar.DestinationPath = tempDir;
                 unrar.Open(rarPath, Unrar.OpenMode.Extract);
                 // Get destination from user
                 while (unrar.ReadHeader())
                 {
                     if (unrar.CurrentFile.FileName.Equals(filePath))
                     {
                         unrar.Extract();
                         break;
                     }
                     unrar.Skip();
                 }
                 unrar.Close();
                 //
                 string tempPath = System.IO.Path.Combine(tempDir, filePath);
                 byte[] buffer = File.ReadAllBytes(tempPath);
                 File.Delete(tempPath); //Remove file
                 return buffer;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }
         return new byte[0];
     }
 }
示例#11
0
        /// <summary>
        /// Reads the next archive header and populates CurrentFile property data
        /// </summary>
        /// <returns></returns>
        public bool ReadHeader()
        {
            // Throw exception if archive not open
            if (this.archiveHandle == IntPtr.Zero)
            {
                throw new IOException("Archive is not open.");
            }

            // Initialize header struct
            this.header = new RARHeaderDataEx();
            header.Initialize();

            // Read next entry
            currentFile = null;
            int result = Unrar.RARReadHeaderEx(this.archiveHandle, ref this.header);

            // Check for error or end of archive
            if ((RarError)result == RarError.EndOfArchive)
            {
                return(false);
            }
            else if ((RarError)result == RarError.BadData)
            {
                throw new IOException("Archive data is corrupt.");
            }

            // Determine if new file
            if (((header.Flags & 0x01) != 0) && currentFile != null)
            {
                currentFile.ContinuedFromPrevious = true;
            }
            else
            {
                // New file, prepare header
                currentFile          = new RARFileInfo();
                currentFile.FileName = header.FileNameW.ToString();
                if ((header.Flags & 0x02) != 0)
                {
                    currentFile.ContinuedOnNext = true;
                }
                if (header.PackSizeHigh != 0)
                {
                    currentFile.PackedSize = (header.PackSizeHigh * 0x100000000) + header.PackSize;
                }
                else
                {
                    currentFile.PackedSize = header.PackSize;
                }
                if (header.UnpSizeHigh != 0)
                {
                    currentFile.UnpackedSize = (header.UnpSizeHigh * 0x100000000) + header.UnpSize;
                }
                else
                {
                    currentFile.UnpackedSize = header.UnpSize;
                }
                currentFile.HostOS          = (int)header.HostOS;
                currentFile.FileCRC         = header.FileCRC;
                currentFile.FileTime        = FromMSDOSTime(header.FileTime);
                currentFile.VersionToUnpack = (int)header.UnpVer;
                currentFile.Method          = (int)header.Method;
                currentFile.FileAttributes  = (int)header.FileAttr;
                currentFile.BytesExtracted  = 0;
                if ((header.Flags & 0xE0) == 0xE0)
                {
                    currentFile.IsDirectory = true;
                }
                this.OnNewFile();
            }

            // Return success
            return(true);
        }
示例#12
0
        /// <summary>
        /// Opens specified archive using the specified mode.
        /// </summary>
        /// <param name="archivePathName">Path of archive to open</param>
        /// <param name="openMode">Mode in which to open archive</param>
        public void Open(string archivePathName, OpenMode openMode)
        {
            IntPtr handle = IntPtr.Zero;

            // Close any previously open archives
            if (this.archiveHandle != IntPtr.Zero)
            {
                this.Close();
            }

            // Prepare extended open archive struct
            this.ArchivePathName = archivePathName;
            RAROpenArchiveDataEx openStruct = new RAROpenArchiveDataEx();

            openStruct.Initialize();
            openStruct.ArcName  = this.archivePathName + "\0";
            openStruct.ArcNameW = this.archivePathName + "\0";
            openStruct.OpenMode = (uint)openMode;
            if (this.retrieveComment)
            {
                openStruct.CmtBuf     = new string((char)0, 65536);
                openStruct.CmtBufSize = 65536;
            }
            else
            {
                openStruct.CmtBuf     = null;
                openStruct.CmtBufSize = 0;
            }

            // Open archive
            handle = Unrar.RAROpenArchiveEx(ref openStruct);

            // Check for success
            if (openStruct.OpenResult != 0)
            {
                switch ((RarError)openStruct.OpenResult)
                {
                case RarError.InsufficientMemory:
                    throw new OutOfMemoryException("Insufficient memory to perform operation.");

                case RarError.BadData:
                    throw new IOException("Archive header broken");

                case RarError.BadArchive:
                    throw new IOException("File is not a valid archive.");

                case RarError.OpenError:
                    throw new IOException("File could not be opened.");
                }
            }

            // Save handle and flags
            this.archiveHandle = handle;
            this.archiveFlags  = (ArchiveFlags)openStruct.Flags;

            // Set callback
            Unrar.RARSetCallback(this.archiveHandle, this.callback, this.GetHashCode());

            // If comment retrieved, save it
            if (openStruct.CmtState == 1)
            {
                this.comment = openStruct.CmtBuf.ToString();
            }

            // If password supplied, set it
            if (this.password.Length != 0)
            {
                Unrar.RARSetPassword(this.archiveHandle, this.password);
            }

            // Fire NewVolume event for first volume
            this.OnNewVolume(this.archivePathName);
        }
示例#13
0
 private void AttachHandlers(Unrar unrar)
 {
     unrar.ExtractionProgress += new ExtractionProgressHandler(unrar_ExtractionProgress);
     unrar.MissingVolume      += new MissingVolumeHandler(unrar_MissingVolume);
     unrar.PasswordRequired   += new PasswordRequiredHandler(unrar_PasswordRequired);
 }
        protected void unrar(string filename, string destination, List<string> extensions)
        {
            Unrar unrar = null;
            try {
                // Create new unrar class and attach event handlers for
                // progress, missing volumes, and password
                unrar = new Unrar();
                //AttachHandlers(unrar);

                // Set destination path for all files
                unrar.DestinationPath = destination;

                // Open archive for extraction
                unrar.Open(filename, Unrar.OpenMode.Extract);

                // Extract each file with subtitle extension
                while (unrar.ReadHeader()) {

                    string extension = Path.GetExtension(unrar.CurrentFile.FileName).Substring(1).ToLower().Replace(".", "");
                    if (extensions.Contains(extension)) {
                        unrar.Extract();
                    }
                    else {
                        unrar.Skip();
                    }
                }
            }
            catch (Exception ex) {
                Logger.Instance.LogMessage("Error during unpack of file: " + filename + " (" + ex.Message + ")", LogLevel.ERROR);
            }
            finally {
                if (unrar != null)
                    unrar.Close();
            }
        }