如何在C#中调用winrar?

lamehsl 2010-11-14 01:30:19
我想在C#中调用winrar ,帮我压缩一些文件,例如我在E 盘下有文件夹 backup ,我想在 e:\rar 目录下建立 backup.rar(e:\backup 文件夹的打包),是如何做的,各位师傅是否有相关代码?
...全文
383 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
开发者孙小聪 2011-03-21
  • 打赏
  • 举报
回复
你们发的哪个 压缩的类是自己写的嘛? 压缩效率咋样???
lamehsl 2010-11-15
  • 打赏
  • 举报
回复
10 楼 谢谢! 但是我只需要 WinRar 的才符合我需要的,用其他的不好。
yc421206 2010-11-15
  • 打赏
  • 举报
回复
dear
您可参考以下连结
http://itgroup.blueshop.com.tw/uuuiii00/AllenJ?n=convew&i=22187
http://itgroup.blueshop.com.tw/uuuiii00/AllenJ?n=convew&i=22187
http://www.cnblogs.com/freeliver54/archive/2007/01/17/622992.aspx
铛铛 2010-11-14
  • 打赏
  • 举报
回复
/// <summary>
/// 压缩和解压文件
/// </summary>
public class ZipClass
{
/// <summary>
/// 所有文件缓存
/// </summary>
List<string> files = new List<string>();

/// <summary>
/// 所有空目录缓存
/// </summary>
List<string> paths = new List<string>();

/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要压缩的文件</param>
/// <param name="zipedFile">压缩后的文件全名</param>
/// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
/// <param name="blockSize">分块大小</param>
public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
{
if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
{
throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
}

FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int size = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, size);

try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (Exception ex)
{
GC.Collect();
throw ex;
}

zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
}

/// <summary>
/// 压缩目录(包括子目录及所有文件)
/// </summary>
/// <param name="rootPath">要压缩的根目录</param>
/// <param name="destinationPath">保存路径</param>
/// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
{
GetAllDirectories(rootPath);

/* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
{

rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"

}
*/
//string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
Crc32 crc = new Crc32();
ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
foreach (string file in files)
{
FileStream fileStream = File.OpenRead(file);//打开压缩文件
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outPutStream.PutNextEntry(entry);
outPutStream.Write(buffer, 0, buffer.Length);
}

this.files.Clear();

foreach (string emptyPath in paths)
{
ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
outPutStream.PutNextEntry(entry);
}

this.paths.Clear();
outPutStream.Finish();
outPutStream.Close();
GC.Collect();
}

/// <summary>
/// 取得目录下所有文件及文件夹,分别存入files及paths
/// </summary>
/// <param name="rootPath">根目录</param>
private void GetAllDirectories(string rootPath)
{
string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
foreach (string path in subPaths)
{
GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
}
string[] files = Directory.GetFiles(rootPath);
foreach (string file in files)
{
this.files.Add(file);//将当前目录中的所有文件全名存入文件List
}
if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录
{
this.paths.Add(rootPath);//记录空目录
}
}

/// <summary>
/// 解压缩文件(压缩文件中含有子目录)
/// </summary>
/// <param name="zipfilepath">待解压缩的文件路径</param>
/// <param name="unzippath">解压缩到指定目录</param>
/// <returns>解压后的文件列表</returns>
public List<string> UnZip(string zipfilepath, string unzippath)
{
//解压出来的文件列表
List<string> unzipFiles = new List<string>();

//检查输出目录是否以“\\”结尾
if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
{
unzippath += "\\";
}

ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(unzippath);
string fileName = Path.GetFileName(theEntry.Name);

//生成解压目录【用户解压到硬盘根目录时,不需要创建】
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(directoryName);
}

if (fileName != String.Empty)
{
//如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
if (theEntry.CompressedSize == 0)
break;
//解压文件到指定的目录
directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
//建立下面的目录和子目录
Directory.CreateDirectory(directoryName);

//记录导出的文件
unzipFiles.Add(unzippath + theEntry.Name);

FileStream streamWriter = File.Create(unzippath + theEntry.Name);

int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
GC.Collect();
return unzipFiles;
}
}
铛铛 2010-11-14
  • 打赏
  • 举报
回复
ICSharpCode.SharpZipLib.dll
__还是少年 2010-11-14
  • 打赏
  • 举报
回复
轻轻飘过...
lamehsl 2010-11-14
  • 打赏
  • 举报
回复
在二楼的代码基础上进行了更改,剔除了代码的一些错误和看不明白的代码,更改如下

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Geoway.HJDMS.Service.Util
{

public class Decompression
{

private string _winrarPath;
private int _exitNum;
public Decompression(string winrarPath)
{
_winrarPath = winrarPath;
}
private void KillWinRar()
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.ProcessName == "WinRAR")
{
process.Kill();
}
}
}
public bool Compress(string targetFileFullName, string destFolderPath)
{
bool Result = false;
try
{
string cmd = string.Format( "A {0} {1} -r ", destFolderPath,targetFileFullName );
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = _winrarPath;
startInfo.Arguments = cmd;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = Path.GetDirectoryName(targetFileFullName);
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
_exitNum = process.ExitCode;
if (_exitNum == 0)
{
Result = true;
}
process.Close();
KillWinRar();
}
catch
{
return Result;
}
return Result;
}

}
}





经过测试,是可以运行。

使用的时候,只需要建立新类(Decompression),就可以使用。

c_fans_2010 2010-11-14
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 lishenghu365 的回复:]
给你一个封装好的类。


C# code

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Geoway.HJDMS.Service.Util
{

public cla……
[/Quote]

帮顶...
lamehsl 2010-11-14
  • 打赏
  • 举报
回复
这个需要每台机子的WINRAR 的安装路径的么?
lamehsl 2010-11-14
  • 打赏
  • 举报
回复
二楼是否可以说明白一点如何使用?
李先生2017 2010-11-14
  • 打赏
  • 举报
回复
给你一个封装好的类。


using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Geoway.HJDMS.Service.Util
{

public class Decompression
{

/// <summary>
/// 解压缩对象初始化
/// </summary>
/// <param name="winrarPath"></param>
/// <param name="decompressionCommand"></param>
public Decompression(string winrarPath, string decompressionCommand)
{
_decompressionCommand = decompressionCommand;
_winrarPath = winrarPath;
}
/// <summary>
/// 解压缩对象初始化
/// </summary>
/// <param name="winrarPath"></param>
public Decompression(string winrarPath)
{
_decompressionCommand = " e -ad -y ";
_winrarPath = winrarPath;
}

#region 私有变量
private string _decompressionCommand;
private string _winrarPath;
private int _exitNum;
#endregion

#region 私有函数
private void KillWinRar()
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.ProcessName == "WinRAR")
{
process.Kill();
}
}
}
private string GetExitInfoByCode(int exitCode)
{
string result = string.Empty;
switch (exitCode)
{
case 0:
result = "成功操作";
break;
case 1:
result = "警告,发生非致命错误";
break;
case 2:
result = "发生致命错误";
break;
case 3:
result = "解压时发生CRC 错误";
break;
case 4:
result = "尝试修改一个锁定的压缩文件";
break;
case 5:
result = "写错误";
break;
case 6:
result = "文件打开错误";
break;
case 7:
result = "错误命令行选项";
break;
case 8:
result = "内存不足";
break;
case 9:
result = "文件创建错误";
break;
case 255:
result = "用户中断";
break;
default:
break;
}
return result;
}
#endregion

#region 外部接口
/// <summary>
/// 解压缩文件
/// </summary>
/// <param name="targetFileFullName"></param>
/// <param name="destFolderPath"></param>
/// <param name="formatOption"></param>
/// <returns></returns>
public bool Extract(string targetFileFullName, string destFolderPath, string formatOption)
{
bool Result = false;
try
{
string cmd = string.Format(_decompressionCommand + " {0} {1} {2} ", targetFileFullName, formatOption, destFolderPath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = _winrarPath;
startInfo.Arguments = cmd;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = Path.GetDirectoryName(targetFileFullName);
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
_exitNum = process.ExitCode;
if (_exitNum == 0)
{
Result = true;
}
process.Close();
KillWinRar();
}
catch
{
return Result;
}
return Result;
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="targetFileFullName"></param>
/// <param name="destFolderPath"></param>
/// <param name="compressCommand"></param>
/// <returns></returns>
public bool Compress(string targetFileFullName, string destFolderPath,string compressCommand)
{
bool Result = false;
try
{
string cmd = string.Format(compressCommand + " {0} {1} ", targetFileFullName, destFolderPath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = _winrarPath;
startInfo.Arguments = cmd;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = Path.GetDirectoryName(targetFileFullName);
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
_exitNum = process.ExitCode;
if (_exitNum == 0)
{
Result = true;
}
process.Close();
KillWinRar();
}
catch
{
return Result;
}
return Result;
}
/// <summary>
/// 获取解压缩结果
/// </summary>
/// <returns></returns>
public string GetExitInfo()
{
string exitInfo = GetExitInfoByCode(_exitNum);
return exitInfo;
}
#endregion
}
}

xshf12345 2010-11-14
  • 打赏
  • 举报
回复
使用Process.Run方法
下面是怎么使用命令行进行压缩的


命令行语法
--------------------------------------------------------------------------------


从命令行也可以运行 WinRAR 命令,常规的命令行语法描述如下:

WinRAR <命令> -<开关1> -<开关N> <压缩文件 > <文件...> <@列表文件...> <解压路径\>

命令 要 WinRAR 运行的字符组合代表功能
开关 切换操作指定类型,压缩强度,压缩文件类型,等等的定义。
压缩文件 要处理的压缩文件名。
文件 要处理的文件名。
列表文件 列表文件是包含要处理文件名称的纯文本。文件名应该在第一卷启动。可以在列表文件中使用 //字符后添加注释。例如,你可以包含两列字符串创建 backup.lst:
c:\work\doc\*.txt //备份文本文档 c:\work\image\*.bmp //备份图片

c:\work\misc

并接着运行:

winrar a backup @backup.lst

你可以在命令行中同时指定普通的文件名和列表文件名。

解压路径 只与命令 e 和 x ,搭配使用。指出解压文件添加的位置。如果文件夹不存在时,会自动创建。

110,570

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧