如何在C#中提取rar文件?
我想提取.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();
的第一次工作得很好,第二次是没有任何显示。
你忘了补充流用于阅读错误。如果WINRAR运行正常,当您添加流来读取它时,您会发现错误输出。
使用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事件 – 2015-02-10 10:23:06
由于Kjartan建议,使用7-Zip的SDK可能比产卵取决于您使用外部可执行一个更好的选择:
7-Zip的SDK是一个C/C++库,但http://sevenzipsharp.codeplex.com/有一个.net库它围绕着7-Zip SDK,这使得它更容易在.NET中使用。
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;
}
}
我做了一个纯粹的C#unrar实现。同样的工作在Silverlight(可能WP & 7)
它支持密码保护的RAR文件吗? – Ali 2012-04-01 10:04:14
目前没有。尽管如此,我打算将其添加到http://sharpcompress.codeplex.com,这是基于nunrar – adamhathcock 2012-04-02 12:50:32
的最新代码清晰明了。谢谢 – 2012-12-29 13:44:07
我得到了答案。 试试这个:
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();
9回答,只SAM穆萨维直接回答你的问题,但没有人的告诉你,什么是错的。从WinRAR的手动举例:
...命令:
WinRAR x Fonts *.ttf NewFonts\
将提取档案的字体* .TTF文件的文件夹NewFonts
您需要在上面的例子中使用尾部的反斜杠作为表示目标文件夹。
而这正是c:\download
所缺少的。现在它试图将文件内的文件 c:\ download提取到当前目录。第一次如何工作是一个谜。
你喜欢这个答案吗?给我一些急需的声望!我几乎可以投票!
我们也可以利用这一点,
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();
会一个PowerShell脚本或命令脚本不是更合适?你有什么特别的理由想在代码中做到这一点? – 2010-07-13 14:33:38
另请参见http://stackoverflow.com/questions/11737/net-library-to-unzip-zip-and-rar-files – 2010-07-13 14:39:40
在上面引用的奇尔卡特库工程治疗。只有刺激才是它的非托管代码。 – Murph 2010-07-13 15:24:37