如何在C#中提取rar文件?

发布于 2024-09-09 11:03:37 字数 519 浏览 4 评论 0 原文

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

第一次运行正常,第二次则什么也不显示。

I want to extract .rar files using cmd shell so I wrote this code:

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

The first time it worked fine, the second time it displayed nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

橘和柠 2024-09-16 11:03:37

使用 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";
                                     }));
    }

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

Use SevenZipSharp as it's a bit better way of doing things then working with some .exe's.

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";
                                     }));
    }

Of course you need to adjust things a bit, and use some of your own stuff. But for the sake of example I've added some additional methods.

一个人的夜不怕黑 2024-09-16 11:03:37

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

另外,您也可以查看 7-zip SDK

You might skip the middle step and call the winrar.exe with the parameters straight instead of first instanciating cmd.exe

Also you might take a look at the 7-zip SDK

悲凉≈ 2024-09-16 11:03:37
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;
    }



}
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;
    }



}
缱倦旧时光 2024-09-16 11:03:37

您忘记添加读取错误的流。如果 WINRAR 运行正常,当您添加流来读取它时,您会发现错误输出。

You forgot to add a stream for reading errors. If WINRAR is behaving properly, you will find your error output when you add the stream to read it.

巷雨优美回忆 2024-09-16 11:03:37

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

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

I Got the answer.
try this one:

 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();
最单纯的乌龟 2024-09-16 11:03:37

正如 Kjartan 所建议的,根据您的用途,使用 7-Zip SDK 可能比生成外部可执行文件更好:

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

As Kjartan suggested, using 7-Zip SDK may be a better option than spawning an external executable depending on your use:

7-Zip SDK is a C/C++ library but http://sevenzipsharp.codeplex.com/ has a .Net library of it around the 7-Zip SDK which makes it easier to use in .NET.

云雾 2024-09-16 11:03:37

我们也可以用这个,

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

We can also use this,

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();
飘逸的'云 2024-09-16 11:03:37

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

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

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

9 Answers, only sam mousavi is answering your question directly, but noone's telling you what's wrong. Citing from the WinRAR manual:

...the command: WinRAR x Fonts *.ttf NewFonts\
will extract *.ttf files from the archive Fonts to the folder NewFonts
You need to use the trailing backslash as in the example above for denoting the destination folder.

And that's exactly what's missing up there at c:\download. Right now it tries to extract the file c:\download inside the archive to the current directory. How it could work the first time is a mystery.

思慕 2024-09-16 11:03:37

您可以直接使用此库: http://sevenziplib.codeplex.com/

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

You can use this lib directly: http://sevenziplib.codeplex.com/

SevenZipLib is a lightweight, easy-to-use managed interface to the 7-zip library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文