ICompress.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Dyne.Compress
{
/// <summary>
/// 压缩解压接口
/// </summary>
public interface ICompress
{
/// <summary>
/// 返回的错误信息
/// </summary>
string ErrMsg { get;}
/// <summary>
/// 压缩算法
/// </summary>
/// <param name="srcFiles">压缩原文件列表</param>
/// <param name="dstCompressFile">压缩目标文件</param>
/// <returns>压缩成功 or 失败</returns>
bool Compress(ArrayList srcFiles, string dstCompressFile);
/// <summary>
/// 解压算法
/// </summary>
/// <param name="compressFileName">解压原文件名</param>
/// <param name="uncompDir">文件释放目录</param>
/// <returns>解压成功 or 失败</returns>
bool UnCompress(string compressFileName, string uncompDir);
}
}
RARCompress.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using Dyne.CommClass;
namespace Dyne.Compress
{
public class RARCompress:ICompress
{
private string m_errMsg;
/// <summary>
/// 利用 WinRAR 进行压缩
/// </summary>
/// <param name="path">将要被压缩的文件夹(绝对路径)</param>
/// <param name="rarPath">压缩后的 .rar 的存放目录(绝对路径)</param>
/// <param name="rarName">压缩文件的名称(包括后缀)</param>
/// <returns>true 或 false。压缩成功返回 true,反之,false。</returns>
//public bool RAR(string path, string rarPath, string rarName)
public bool RAR(string path, string rarName)
{
string rarPath = "";
FileInfo fi= new FileInfo(rarName.Split(new char[]{' '})[0].Replace("\"",""));
rarPath = fi.DirectoryName;
bool flag = false;
string rarexe; //WinRAR.exe 的完整路径
RegistryKey regkey; //注册表键
Object regvalue; //键值
string cmd; //WinRAR 命令参数
ProcessStartInfo startinfo;
Process process;
try
{
//regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
//regvalue = regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1"
//if (regvalue == null||regvalue=="")
//{
// m_errMsg = "没有安装WinRAR压缩软件";
// return false;
//}
//rarexe = regvalue.ToString();
//regkey.Close();
//rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe
Directory.CreateDirectory(path);
//压缩命令,相当于在要压缩的文件夹(path)上点右键->WinRAR->添加到压缩文件->输入压缩文件名(rarName)
//cmd = string.Format("a -r {0} {1} ",
cmd = string.Format(" a -ep -ibck -afzip {0}.zip {1}",
path,
rarName);
startinfo = new ProcessStartInfo();
startinfo.FileName = "winrar.exe";//rarexe;//
startinfo.Arguments = cmd; //设置命令参数
startinfo.UseShellExecute = true;
startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口
//startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit(); //无限期等待进程 winrar.exe 退出
if (process.HasExited)
{
flag = true;
}
if (Directory.Exists(path))
Directory.Delete(path);
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}
/// <summary>
/// 利用 WinRAR 进行解压缩
/// </summary>
/// <param name="path">文件解压路径(绝对)</param>
/// <param name="rarPath">将要解压缩的 .zip 文件的存放目录(绝对路径)</param>
/// <param name="rarName">将要解压缩的 .zip 文件名(包括后缀)</param>
/// <returns>true 或 false。解压缩成功返回 true,反之,false。</returns>
//public bool UnRAR(string path, string rarPath, string rarName)
public bool UnRAR(string path, string rarName)
{
bool flag = false;
string rarexe;
RegistryKey regkey;
Object regvalue;
string cmd;
ProcessStartInfo startinfo;
Process process;
try
{
//regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
//regvalue = regkey.GetValue("");
//if (regvalue == null || regvalue == "")
//{
// m_errMsg = "没有安装WinRAR压缩软件";
// return false;
//}
//rarexe = regvalue.ToString();
//regkey.Close();
//rarexe = rarexe.Substring(1, rarexe.Length - 7);
Directory.CreateDirectory(path);
//解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹
cmd = string.Format("x -y {0} {1} ",
rarName,
path);
startinfo = new ProcessStartInfo();
startinfo.FileName = "winrar.exe";//rarexe;//
startinfo.Arguments = cmd;
startinfo.WindowStyle = ProcessWindowStyle.Hidden;
//startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit();
if (process.HasExited)
{
flag = true;
}
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}
#region ICompress 成员
public string ErrMsg
{
get { return m_errMsg; }
}
public bool Compress(System.Collections.ArrayList srcFiles, string dstCompressFile)
{
string rarname = "";
bool bRslt = false;
for(int i=0;i<srcFiles.Count;i++)
{
if (i == 0)
{
rarname = string.Format("\"{0}\"", srcFiles[0]);
}
else
{
rarname += string.Format(" \"{0}\"", srcFiles[i]);
}
}
try
{
bRslt = RAR(dstCompressFile, rarname);
}
catch(Exception e)
{
Dyne.CommClass.EventLog.WriteErrorLog("压缩文件出错", e);
return false;
}
return bRslt;
}
public bool UnCompress(string compressFileName, string uncompDir)
{
bool bRslt = false;
try
{
bRslt = UnRAR(uncompDir, compressFileName);
}
catch (Exception e)
{
Dyne.CommClass.EventLog.WriteErrorLog(string.Format("解压文件:{0}出错", compressFileName), e);
return false;
}
return bRslt;
}
#endregion
}
}
ZIPCompress.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.Checksums;
namespace Dyne.Compress
{
public class CompressFactory
{
public static ICompress CreateZIP()
{
return new ZIPCompress();
}
public static ICompress CreateRAR()
{
return new RARCompress();
}
}
internal class ZIPCompress : ICompress
{
/// <summary>
/// 错误信息
/// </summary>
private string m_errMsg;
#region ICompress 成员
/// <summary>
/// 错误信息
/// </summary>
public string ErrMsg
{
get { return m_errMsg; }
}
/// <summary>
/// 压缩算法
/// </summary>
/// <param name="p_strFiles">压缩原文件列表</param>
/// <param name="p_ziptoFileName">压缩目标文件</param>
/// <returns>压缩成功 or 失败</returns>
public bool Compress(ArrayList p_strFiles, string p_ziptoFileName)
{
string strPhysicalPath = p_ziptoFileName;
string strZipFileName = strPhysicalPath + ".zip";
if (File.Exists(strZipFileName))
{
File.Delete(strZipFileName);
}
//需要压缩的文件数
string[] strFilePaths = new string[p_strFiles.Count];
MemoryStream oMemoryStream = new MemoryStream();
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(strZipFileName));
try
{
for (int i = 0; i <= p_strFiles.Count - 1; i++)
{
//如果是zip文件,就不压缩
if (p_strFiles[i].ToString().Contains("zip"))
continue;
#region 读文件数据到流
FileStream oReadFileStream = File.OpenRead(p_strFiles[i].ToString());
byte[] btFile = new byte[oReadFileStream.Length];
oReadFileStream.Read(btFile, 0, btFile.Length);
#endregion
string strCurrentFileName = Path.GetFileName(p_strFiles[i].ToString());
strFilePaths[i] = strPhysicalPath + "/" + strCurrentFileName;
ZipEntry oZipEntry = new ZipEntry(strCurrentFileName);
oZipEntry.DateTime = DateTime.Now;
oZipEntry.Size = oReadFileStream.Length;
Crc32 oCrc32 = new Crc32();
oCrc32.Reset();
oCrc32.Update(btFile);
oZipEntry.Crc = oCrc32.Value;
oZipStream.PutNextEntry(oZipEntry);
oZipStream.Write(btFile, 0, btFile.Length);
oReadFileStream.Close();
}
//oZipStream.Finish();
//oZipStream.Close();
}
catch (Exception exp)
{
/// Write Error Log
//oZipStream.Finish();
//oZipStream.Close();
m_errMsg = exp.Message;
Dyne.CommClass.EventLog.WriteErrorLog("压缩文件出错", exp);
return false;
}
finally
{
if (oZipStream != null)
{
oZipStream.Finish();
oZipStream.Close();
}
}
return true;
}
/// <summary>
/// 解压算法
/// </summary>
/// <param name="p_strFile">解压原文件名</param>
/// <param name="p_strDir">文件释放目录</param>
/// <returns>解压成功 or 失败</returns>
public bool UnCompress(string p_strFile, string p_strDir)
{
#region 说明
/*
///
/// 功能:将一个压缩文件解压缩到一个目录下
///
/// 参数:
/// strFile:压缩文件
/// strDir:解压缩目录
///
/// 返回:
/// 无
///*/
#endregion
ZipInputStream s;
ZipEntry theEntry;
try
{
if (p_strDir == "") p_strDir = Directory.GetCurrentDirectory();
if (!p_strDir.EndsWith(@"\")) p_strDir = p_strDir + @"\";
s = new ZipInputStream(File.OpenRead(p_strFile));
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = "";
string pathToZip = "";
pathToZip = theEntry.Name;
if (pathToZip != "")
directoryName = Path.GetDirectoryName(pathToZip) + @"\";
string fileName = Path.GetFileName(pathToZip);
Directory.CreateDirectory(p_strDir + directoryName);
if (fileName != "")
{
FileStream streamWriter = File.Create(p_strDir + directoryName + fileName);
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();
}
catch (Exception exp)
{
/// Write Error Log
m_errMsg = exp.Message;
Dyne.CommClass.EventLog.WriteErrorLog(string.Format("解压文件:{0}出错",p_strFile), exp);
return false;
}
return true;
}
#endregion
}
}