如何在C#中解压一个rar文件?

问题描述 投票:4回答:9

我想用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(); 

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

c# .net compression
9个回答
4
投票

使用 七匹狼 因为这是一种比使用一些.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";
                                     }));
    }

当然,你需要调整一些东西,并使用一些你自己的东西。但为了举例说明,我已经添加了一些额外的方法。


3
投票

你可以跳过中间的步骤,直接调用带有参数的winrar.exe,而不是先实例化cmd.exe。

你也可以看看 7-zip SDK


2
投票
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;
    }



}

1
投票

你忘了添加一个读取错误的流。 如果WINRAR表现正常的话,当你添加流读取的时候,你会发现你的错误输出。


1
投票

我知道答案了,试试这个。

 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();

0
投票

正如Kjartan所建议的,使用7 -Zip SDK可能是一个更好的选择,而不是根据你的使用情况来生成一个外部可执行文件。

7 -Zip SDK是一个CC++库,但是... http:/sevenzipsharp.codeplex.com 围绕7-Zip SDK有一个.Net的库,这使得它在.NET中使用起来更加方便。


0
投票

我们也可以使用这个。

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();

0
投票

9个回答,只有sam mousavi在直接回答你的问题,但是没有人告诉你是什么问题。引自WinRAR手册。

...命令: WinRAR x Fonts *.ttf NewFonts\ 将提取*.ttf文件 从存档Fonts到文件夹NewFonts 你需要使用尾部的反斜杠,就像上面的例子一样,表示目标文件夹。

而这正是在上面缺少的东西 c:\download. 现在,它试图提取文件 c:下载 内的存档到当前目录。第一次怎么能成功,这是个谜。


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.