【问题标题】:How to extract a rar file in C#?如何在 C# 中提取 rar 文件?
【发布时间】:2010-07-13 14:28:06
【问题描述】:

我想使用 cmd shell 提取 .rar 文件,所以我写了这段代码:

string commandLine = @"c:\progra~1\winrar\winrar e  c:\download\TestedU.rar c:\download";
ProcessStartInfo PSI = new ProcessStartInfo("cmd.exe");
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.RedirectStandardError = true;
PSI.UseShellExecute = false;
Process p = Process.Start(PSI);
StreamWriter SW = p.StandardInput;
StreamReader SR = p.StandardOutput;
SW.WriteLine(commandLine);
SW.Close(); 

第一次正常,第二次什么都不显示。

【问题讨论】:

  • powershell 或 cmd 脚本会不会更合适?您有什么特殊原因要在代码中执行此操作吗?
  • 上面引用的 Chilkat 库是一种享受。唯一令人恼火的是它的非托管代码。

标签: c# .net compression


【解决方案1】:

使用SevenZipSharp,因为它比使用某些 .exe 文件更好。

private ReadOnlyCollection<string> ExtractArchive(string varPathToFile, string varDestinationDirectory) {
        ReadOnlyCollection<string> readOnlyArchiveFilenames;
        ReadOnlyCollection<string> readOnlyVolumeFilenames;
        varExtractionFinished = false;
        varExtractionFailed = false;
        SevenZipExtractor.SetLibraryPath(sevenZipDll);
        string fileName = "";
        string directory = "";
        Invoke(new SetNoArgsDelegate(() => {
                                         fileName = varPathToFile;
                                         directory = varDestinationDirectory;
                                     }));
        using (SevenZipExtractor extr = new SevenZipExtractor(fileName)) {
            //string[] test = extr.ArchiveFileNames.

            readOnlyArchiveFilenames = extr.ArchiveFileNames;
            readOnlyVolumeFilenames = extr.VolumeFileNames;
            //foreach (string dinosaur in readOnlyDinosaurs) {
            //MessageBox.Show(dinosaur);
            // }
            //foreach (string dinosaur in readOnlyDinosaurs1) {
            // // MessageBox.Show(dinosaur);
            // }
            try {
            extr.Extracting += extr_Extracting;
            extr.FileExtractionStarted += extr_FileExtractionStarted;
            extr.FileExists += extr_FileExists;
            extr.ExtractionFinished += extr_ExtractionFinished;

                extr.ExtractArchive(directory);
            } catch (FileNotFoundException error) {
                if (varExtractionCancel) {
                    LogBoxTextAdd("[EXTRACTION WAS CANCELED]");
                } else {
                    MessageBox.Show(error.ToString(), "Error with extraction");
                    varExtractionFailed = true;
                }
            }
        }
        varExtractionFinished = true;
        return readOnlyVolumeFilenames;
    }

  private void extr_FileExists(object sender, FileOverwriteEventArgs e) {
        listViewLogFile.Invoke(new SetOverwriteDelegate((args) => LogBoxTextAdd(String.Format("Warning: \"{0}\" already exists; overwritten\r\n", args.FileName))), e);
    }
    private void extr_FileExtractionStarted(object sender, FileInfoEventArgs e) {
        listViewLogFile.Invoke(new SetInfoDelegate((args) => LogBoxTextAdd(String.Format("Extracting \"{0}\"", args.FileInfo.FileName))), e);
    }
    private void extr_Extracting(object sender, ProgressEventArgs e) {
        progressBarCurrentExtract.Invoke(new SetProgressDelegate((args) => progressBarCurrentExtract.Increment(args.PercentDelta)), e);
    }
    private void extr_ExtractionFinished(object sender, EventArgs e) {
        Invoke(new SetNoArgsDelegate(() => {
                                         //pb_ExtractWork.Style = ProgressBarStyle.Blocks;
                                         progressBarCurrentExtract.Value = 0;
                                         varExtractionFinished = true;
                                         //l_ExtractProgress.Text = "Finished";
                                     }));
    }

当然,您需要稍微调整一下,并使用一些您自己的东西。但为了举例,我添加了一些额外的方法。

【讨论】:

  • 有没有 syc 方法来提取档案?我的意思是不使用 ExtractionFinished 事件
【解决方案2】:

您可以跳过中间步骤,直接使用参数调用 winrar.exe,而不是先实例化 cmd.exe

你也可以看看7-zip SDK

【讨论】:

    【解决方案3】:
    UnRar("C:\\Download\\sampleextractfolder\\", filepath2);
    
    private static void UnRar(string WorkingDirectory, string filepath)
    {
    
        // Microsoft.Win32 and System.Diagnostics namespaces are imported
    
        //Dim objRegKey As RegistryKey
        RegistryKey objRegKey;
        objRegKey = Registry.ClassesRoot.OpenSubKey("WinRAR\\Shell\\Open\\Command");
        // Windows 7 Registry entry for WinRAR Open Command
    
        // Dim obj As Object = objRegKey.GetValue("");
        Object obj = objRegKey.GetValue("");
    
        //Dim objRarPath As String = obj.ToString()
        string objRarPath = obj.ToString();
        objRarPath = objRarPath.Substring(1, objRarPath.Length - 7);
    
        objRegKey.Close();
    
        //Dim objArguments As String
        string objArguments;
        // in the following format
        // " X G:\Downloads\samplefile.rar G:\Downloads\sampleextractfolder\"
        objArguments = " X " + " " + filepath + " " + " " + WorkingDirectory;
    
        // Dim objStartInfo As New ProcessStartInfo()
        ProcessStartInfo objStartInfo = new ProcessStartInfo();
    
        // Set the UseShellExecute property of StartInfo object to FALSE
        //Otherwise the we can get the following error message
        //The Process object must have the UseShellExecute property set to false in order to use environment variables.
        objStartInfo.UseShellExecute = false;
        objStartInfo.FileName = objRarPath;
        objStartInfo.Arguments = objArguments;
        objStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        objStartInfo.WorkingDirectory = WorkingDirectory + "\\";
    
        //   Dim objProcess As New Process()
        Process objProcess = new Process();
        objProcess.StartInfo = objStartInfo;
        objProcess.Start();
        objProcess.WaitForExit();
    
    
        try
        {
            FileInfo file = new FileInfo(filepath);
            file.Delete();
        }
        catch (FileNotFoundException e)
        {
            throw e;
        }
    
    
    
    }
    

    【讨论】:

      【解决方案4】:

      您忘记为读取错误添加流。如果 WINRAR 行为正常,您将在添加流以读取它时发现错误输出。

      【讨论】:

        【解决方案5】:

        我得到了答案。 试试这个:

         System.Diagnostics.Process proc = new System.Diagnostics.Process();
         //Put the path of installed winrar.exe
         proc.StartInfo.FileName = @"C:\Program Files\WinRAR\unrar.exe";
         proc.StartInfo.CreateNoWindow = true;
         proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         proc.EnableRaisingEvents = true;
        
         //PWD: Password if the file has any
         //SRC: The path of your rar file. e.g: c:\temp\abc.rar
         //DES: The path you want it to be extracted. e.g: d:\extracted
        
         //ATTENTION: DESTINATION FOLDER MUST EXIST!
        
         proc.StartInfo.Arguments = String.Format("x -p{0} {1} {2}", PWD, SRC, DES);
        
        
         proc.Start();
        

        【讨论】:

          【解决方案6】:

          正如 Kjartan 所建议的,使用 7-Zip SDK 可能比生成外部可执行文件更好,具体取决于您的使用情况:

          7-Zip SDK 是一个 C/C++ 库,但 http://sevenzipsharp.codeplex.com/ 有一个围绕 7-Zip SDK 的 .Net 库,使其更易于在 .NET 中使用。

          【讨论】:

            【解决方案7】:

            我们也可以用这个,

            string SourceFile = @"G:\SourceFolder\125.rar";
            string DestinationPath = @"G:\Destination\";
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = @"G:\Software\WinRAR.exe";
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.EnableRaisingEvents = false;            
            process.StartInfo.Arguments = string.Format("x -o+ \"{0}\" \"{1}\"", SourceFile, DestinationPath);
            process.Start();
            

            【讨论】:

              【解决方案8】:

              9 个答案,只有 sam mousavi 直接回答您的问题,但没有人告诉您出了什么问题。引用自 WinRAR 手册:

              ...命令:WinRAR x Fonts *.ttf NewFonts\
              将从存档字体中提取 *.ttf 文件到文件夹 NewFonts
              您需要使用上面示例中的尾部反斜杠来表示目标文件夹。

              这正是c:\download 所缺少的。现在它尝试将存档中的文件 c:\download 提取到当前目录。第一次如何工作是个谜。

              【讨论】:

                【解决方案9】:

                你可以直接使用这个库:http://sevenziplib.codeplex.com/

                SevenZipLib 是 7-zip 库的轻量级、易于使用的托管接口。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-11-09
                  • 2018-10-23
                  • 2015-10-01
                  • 1970-01-01
                  • 2012-07-15
                  • 2014-12-09
                  • 1970-01-01
                  • 2012-07-23
                  相关资源
                  最近更新 更多