2010-07-13 98 views
3

我想提取.rar程序使用CMD外殼文件,所以我寫了這個代碼:如何在C#中提取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(); 

的第一次工作得很好,第二次是沒有任何顯示。

+0

會一個PowerShell腳本或命令腳本不是更合適?你有什麼特別的理由想在代碼中做到這一點? – 2010-07-13 14:33:38

+0

另請參見http://stackoverflow.com/questions/11737/net-library-to-unzip-zip-and-rar-files – 2010-07-13 14:39:40

+0

在上面引用的奇爾卡特庫工程治療。只有刺激纔是它的非託管代碼。 – Murph 2010-07-13 15:24:37

回答

2

您可能會跳過中間步驟,並且調用帶有參數的WinRAR.exe直的而不是第一instanciating CMD.EXE

你也不妨來看看在7-zip SDK

1

你忘了補充流用於閱讀錯誤。如果WINRAR運行正常,當您添加流來讀取它時,您會發現錯誤輸出。

3

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

當然,你需要調整一些東西,並使用一些你自己的東西。但爲了舉例,我添加了一些其他方法。

+0

是否有任何syc方法來提取檔案?我的意思是沒有使用ExtractionFinished事件 – 2015-02-10 10:23:06

0

由於Kjartan建議,使用7-Zip的SDK可能比產卵取決於您使用外部可執行一個更好的選擇:

7-Zip的SDK是一個C/C++庫,但http://sevenzipsharp.codeplex.com/有一個.net庫它圍繞着7-Zip SDK,這使得它更容易在.NET中使用。

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



} 
3

我做了一個純粹的C#unrar實現。同樣的工作在Silverlight(可能WP & 7)

http://nunrar.codeplex.com/

+0

它支持密碼保護的RAR文件嗎? – Ali 2012-04-01 10:04:14

+0

目前沒有。儘管如此,我打算將其添加到http://sharpcompress.codeplex.com,這是基於nunrar – adamhathcock 2012-04-02 12:50:32

+0

的最新代碼清晰明瞭。謝謝 – 2012-12-29 13:44:07

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 = 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

9回答,只SAM穆薩維直接回答你的問題,但沒有人的告訴你,什麼是錯的。從WinRAR的手動舉例:

...命令:WinRAR x Fonts *.ttf NewFonts\
將提取檔案的字體* .TTF文件的文件夾NewFonts
您需要在上面的例子中使用尾部的反斜槓作爲表示目標文件夾。

而這正是c:\download所缺少的。現在它試圖將文件內的文件 c:\ download提取到當前目錄。第一次如何工作是一個謎。

你喜歡這個答案嗎?給我一些急需的聲望!我幾乎可以投票!

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