C#中文件压缩操作的一个类
2008-03-27 15:33 蓝之风 阅读(641) 评论(3) 编辑 收藏 举报
在做项目的时候经常会用到文件的要所或者是解压缩,这里提供一个文件的压缩操作的类
在做项目的时候经常会用到文件的要所或者是解压缩,这里提供一个文件的压缩操作的类
public class ZIPPER : IDisposable
{
private string m_FolderToZIP;
private ArrayList m_FileNamesToZIP;
private string m_FileNameZipped;
private ZipOutputStream m_ZipStream = null;
private Crc32 m_Crc;
Begin for Public Properties#region Begin for Public Properties
/**//**//**//// <summary>
/// 保存压缩文件的路径
/// </summary>
public string FolderToZIP
{
get { return m_FolderToZIP; }
set { m_FolderToZIP = value; }
}
/**//**//**//// <summary>
/// 要压缩的文件或文件夹
/// </summary>
public ArrayList FileNamesToZIP
{
get { return m_FileNamesToZIP; }
set { m_FileNamesToZIP = value; }
}
/**//**//**//// <summary>
/// 压缩后的文件路径
/// </summary>
public string FileNameZipped
{
get { return m_FileNameZipped; }
set { m_FileNameZipped = value; }
}
#endregion
/**//**//**//// <summary>
/// The construct
/// </summary>
public ZIPPER()
{
this.m_FolderToZIP = "";
this.m_FileNamesToZIP = new ArrayList();
this.m_FileNameZipped = "";
}
ZipFolder#region ZipFolder
/**//**//**//// <summary>
/// Zip one folder : single level
/// Before doing this event, you must set the Folder and the ZIP file name you want
/// </summary>
public void ZipFolder()
{
if (this.m_FolderToZIP.Trim().Length == 0)
{
throw new Exception("You must setup the folder name you want to zip!");
}
if(Directory.Exists(this.m_FolderToZIP) == false)
{
throw new Exception("The folder you input does not exist! Please check it!");
}
if (this.m_FileNameZipped.Trim().Length == 0)
{
throw new Exception("You must setup the zipped file name!");
}
string[] fileNames = Directory.GetFiles(this.m_FolderToZIP.Trim());
if (fileNames.Length == 0)
{
throw new Exception("Can not find any file in this folder(" + this.m_FolderToZIP + ")!");
}
// Create the Zip File
this.CreateZipFile(this.m_FileNameZipped);
// Zip all files
foreach(string file in fileNames)
{
this.ZipSingleFile(file);
}
// Close the Zip File
this.CloseZipFile();
}
#endregion
ZipFiles#region ZipFiles
/**//**//**//// <summary>
/// Zip files
/// Before doing this event, you must set the Files name and the ZIP file name you want
/// </summary>
public void ZipFiles()
{
if (this.m_FileNamesToZIP.Count == 0)
{
throw new Exception("You must setup the files name you want to zip!");
}
foreach(object file in this.m_FileNamesToZIP)
{
if(File.Exists(((string)file).Trim()) == false)
{
throw new Exception("The file(" + (string)file + ") you input does not exist! Please check it!");
}
}
if (this.m_FileNameZipped.Trim().Length == 0)
{
throw new Exception("You must input the zipped file name!");
}
// Create the Zip File
this.CreateZipFile(this.m_FileNameZipped);
// Zip this File
foreach(object file in this.m_FileNamesToZIP)
{
this.ZipSingleFile((string)file);
}
// Close the Zip File
this.CloseZipFile();
}
#endregion
CreateZipFile#region CreateZipFile
/**//**//**//// <summary>
/// Create Zip File by FileNameZipped
/// </summary>
/// <param name="fileNameZipped">zipped file name like "C:TestMyZipFile.ZIP"</param>
private void CreateZipFile(string fileNameZipped)
{
this.m_Crc = new Crc32();
this.m_ZipStream = new ZipOutputStream(File.Create(fileNameZipped));
this.m_ZipStream.SetLevel(6); // 0 - store only to 9 - means best compression
}
#endregion
CloseZipFile#region CloseZipFile
/**//**//**//// <summary>
/// Close the Zip file
/// </summary>
private void CloseZipFile()
{
this.m_ZipStream.Finish();
this.m_ZipStream.Close();
this.m_ZipStream = null;
}
#endregion
ZipSingleFile#region ZipSingleFile
/**//**//**//// <summary>
/// Zip single file
/// </summary>
/// <param name="fileName">file name like "C:TestTest.txt"</param>
private void ZipSingleFile(string fileNameToZip)
{
// Open and read this file
FileStream fso = File.OpenRead(fileNameToZip);
// Read this file to Buffer
byte[] buffer = new byte[fso.Length];
fso.Read(buffer,0,buffer.Length);
// Create a new ZipEntry
ZipEntry zipEntry = new ZipEntry(fileNameToZip.Split('\\')[fileNameToZip.Split('\\').Length - 1]);
//ZipEntry zipEntry = new ZipEntry(fileNameToZip);
zipEntry.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.
zipEntry.Size = fso.Length;
fso.Close();
fso = null;
// Using CRC to format the buffer
this.m_Crc.Reset();
this.m_Crc.Update(buffer);
zipEntry.Crc = this.m_Crc.Value;
// Add this ZipEntry to the ZipStream
this.m_ZipStream.PutNextEntry(zipEntry);
this.m_ZipStream.Write(buffer,0,buffer.Length);
}
#endregion
IDisposable member#region IDisposable member
/**//**//**//// <summary>
/// Release all objects
/// </summary>
public void Dispose()
{
if(this.m_ZipStream != null)
{
this.m_ZipStream.Close();
this.m_ZipStream = null;
}
}
#endregion
将文件夹压缩文件#region 将文件夹压缩文件
private ZipOutputStream zos = null;
private string strBaseDir = "";
/**//// <summary>
///
/// </summary>
/// <param name="strPath">要压缩的文件路径</param>
/// <param name="strFileName">压缩后的文件名</param>
public void DirectoryToZip(string strPath, string strFileName)
{
MemoryStream ms = null;
HttpContext.Current.Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
public void addZipEntry(string PathStr)
{
DirectoryInfo di = new DirectoryInfo(PathStr);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
ZipEntry entry = new ZipEntry(strEntryName);
//ZipEntry entry = new ZipEntry(strEntryName.Split('\\')[strEntryName.Split('\\').Length - 1]);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
#endregion
===压缩然后输出到页面===#region ===压缩然后输出到页面===
/**//// <summary>
/// 压缩然后输出到页面
/// </summary>
/// <param name="inputdirectory">输入文件夹</param>
/// <param name="tmpdirectory">输出临时文件夹</param>
/// <param name="strFileName">输出下载的文件名</param>
public static void PackFiles(string inputdirectory, string tmpdirectory, string strFileName)
{
string exportfile = tmpdirectory + strFileName + ".ZIP";
try
{
FastZip fz = new FastZip();
fz.CreateEmptyDirectories = true;
fz.CreateZip(exportfile, inputdirectory, true, "");
fz = null;
try
{
//删除临时文件
Directory.Delete(inputdirectory, true);
}
catch
{
}
DownLoadUtils.ExportFile(exportfile, strFileName + ".ZIP", true);
}
catch (Exception ex)
{
throw;
}
}
#endregion
}
===解压===#region ===解压===
public class ZipUtils
{
public class UnzipException : ApplicationException
{
public UnzipException(string msg) : base(msg) { }
}
/**//// <summary>
/// 解压缩文件到指定目录
/// </summary>
/// <param name="filePath">表示压缩文件所在的路径</param>
/// <param name="extractFolder">表示解压缩后文件存放的目录</param>
public static void UnzipPack(string filePath, string extractFolder)
{
ZipConstants.DefaultCodePage = 936;//中文
ZipInputStream s = null;
try
{
s = new ZipInputStream(File.OpenRead(filePath));
//zip文件的入口类
ZipEntry theEntry;
//遍历压缩文件的所有入口
while (null != (theEntry = s.GetNextEntry()))
{
//设置解压文件目录名和文件名
//string directoryName = Path.GetDirectoryName ( extractFolder );
string directoryName = extractFolder;
//MessageBox.Show("directoryName:{0}",directoryName );
string fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
Directory.CreateDirectory(directoryName);
if (String.Empty != fileName)
{
//解压文件到指定文件夹
string path = directoryName + "/" + theEntry.Name;
FileInfo fileInfo = new FileInfo(path);
string str = path.Substring(0, path.Length - fileInfo.Name.Length - 1);
//MessageBox.Show(path );
if (!Directory.Exists(str)) Directory.CreateDirectory(str);
FileStream streamWriter = File.Create(path);
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();
}
}
}
catch
{
throw new UnzipException("ZipFileNotFound");
}
finally
{
s.Close();
}
}
}
#endregion
{
private string m_FolderToZIP;
private ArrayList m_FileNamesToZIP;
private string m_FileNameZipped;
private ZipOutputStream m_ZipStream = null;
private Crc32 m_Crc;
Begin for Public Properties#region Begin for Public Properties
/**//**//**//// <summary>
/// 保存压缩文件的路径
/// </summary>
public string FolderToZIP
{
get { return m_FolderToZIP; }
set { m_FolderToZIP = value; }
}
/**//**//**//// <summary>
/// 要压缩的文件或文件夹
/// </summary>
public ArrayList FileNamesToZIP
{
get { return m_FileNamesToZIP; }
set { m_FileNamesToZIP = value; }
}
/**//**//**//// <summary>
/// 压缩后的文件路径
/// </summary>
public string FileNameZipped
{
get { return m_FileNameZipped; }
set { m_FileNameZipped = value; }
}
#endregion
/**//**//**//// <summary>
/// The construct
/// </summary>
public ZIPPER()
{
this.m_FolderToZIP = "";
this.m_FileNamesToZIP = new ArrayList();
this.m_FileNameZipped = "";
}
ZipFolder#region ZipFolder
/**//**//**//// <summary>
/// Zip one folder : single level
/// Before doing this event, you must set the Folder and the ZIP file name you want
/// </summary>
public void ZipFolder()
{
if (this.m_FolderToZIP.Trim().Length == 0)
{
throw new Exception("You must setup the folder name you want to zip!");
}
if(Directory.Exists(this.m_FolderToZIP) == false)
{
throw new Exception("The folder you input does not exist! Please check it!");
}
if (this.m_FileNameZipped.Trim().Length == 0)
{
throw new Exception("You must setup the zipped file name!");
}
string[] fileNames = Directory.GetFiles(this.m_FolderToZIP.Trim());
if (fileNames.Length == 0)
{
throw new Exception("Can not find any file in this folder(" + this.m_FolderToZIP + ")!");
}
// Create the Zip File
this.CreateZipFile(this.m_FileNameZipped);
// Zip all files
foreach(string file in fileNames)
{
this.ZipSingleFile(file);
}
// Close the Zip File
this.CloseZipFile();
}
#endregion
ZipFiles#region ZipFiles
/**//**//**//// <summary>
/// Zip files
/// Before doing this event, you must set the Files name and the ZIP file name you want
/// </summary>
public void ZipFiles()
{
if (this.m_FileNamesToZIP.Count == 0)
{
throw new Exception("You must setup the files name you want to zip!");
}
foreach(object file in this.m_FileNamesToZIP)
{
if(File.Exists(((string)file).Trim()) == false)
{
throw new Exception("The file(" + (string)file + ") you input does not exist! Please check it!");
}
}
if (this.m_FileNameZipped.Trim().Length == 0)
{
throw new Exception("You must input the zipped file name!");
}
// Create the Zip File
this.CreateZipFile(this.m_FileNameZipped);
// Zip this File
foreach(object file in this.m_FileNamesToZIP)
{
this.ZipSingleFile((string)file);
}
// Close the Zip File
this.CloseZipFile();
}
#endregion
CreateZipFile#region CreateZipFile
/**//**//**//// <summary>
/// Create Zip File by FileNameZipped
/// </summary>
/// <param name="fileNameZipped">zipped file name like "C:TestMyZipFile.ZIP"</param>
private void CreateZipFile(string fileNameZipped)
{
this.m_Crc = new Crc32();
this.m_ZipStream = new ZipOutputStream(File.Create(fileNameZipped));
this.m_ZipStream.SetLevel(6); // 0 - store only to 9 - means best compression
}
#endregion
CloseZipFile#region CloseZipFile
/**//**//**//// <summary>
/// Close the Zip file
/// </summary>
private void CloseZipFile()
{
this.m_ZipStream.Finish();
this.m_ZipStream.Close();
this.m_ZipStream = null;
}
#endregion
ZipSingleFile#region ZipSingleFile
/**//**//**//// <summary>
/// Zip single file
/// </summary>
/// <param name="fileName">file name like "C:TestTest.txt"</param>
private void ZipSingleFile(string fileNameToZip)
{
// Open and read this file
FileStream fso = File.OpenRead(fileNameToZip);
// Read this file to Buffer
byte[] buffer = new byte[fso.Length];
fso.Read(buffer,0,buffer.Length);
// Create a new ZipEntry
ZipEntry zipEntry = new ZipEntry(fileNameToZip.Split('\\')[fileNameToZip.Split('\\').Length - 1]);
//ZipEntry zipEntry = new ZipEntry(fileNameToZip);
zipEntry.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.
zipEntry.Size = fso.Length;
fso.Close();
fso = null;
// Using CRC to format the buffer
this.m_Crc.Reset();
this.m_Crc.Update(buffer);
zipEntry.Crc = this.m_Crc.Value;
// Add this ZipEntry to the ZipStream
this.m_ZipStream.PutNextEntry(zipEntry);
this.m_ZipStream.Write(buffer,0,buffer.Length);
}
#endregion
IDisposable member#region IDisposable member
/**//**//**//// <summary>
/// Release all objects
/// </summary>
public void Dispose()
{
if(this.m_ZipStream != null)
{
this.m_ZipStream.Close();
this.m_ZipStream = null;
}
}
#endregion
将文件夹压缩文件#region 将文件夹压缩文件
private ZipOutputStream zos = null;
private string strBaseDir = "";
/**//// <summary>
///
/// </summary>
/// <param name="strPath">要压缩的文件路径</param>
/// <param name="strFileName">压缩后的文件名</param>
public void DirectoryToZip(string strPath, string strFileName)
{
MemoryStream ms = null;
HttpContext.Current.Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
public void addZipEntry(string PathStr)
{
DirectoryInfo di = new DirectoryInfo(PathStr);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
ZipEntry entry = new ZipEntry(strEntryName);
//ZipEntry entry = new ZipEntry(strEntryName.Split('\\')[strEntryName.Split('\\').Length - 1]);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
#endregion
===压缩然后输出到页面===#region ===压缩然后输出到页面===
/**//// <summary>
/// 压缩然后输出到页面
/// </summary>
/// <param name="inputdirectory">输入文件夹</param>
/// <param name="tmpdirectory">输出临时文件夹</param>
/// <param name="strFileName">输出下载的文件名</param>
public static void PackFiles(string inputdirectory, string tmpdirectory, string strFileName)
{
string exportfile = tmpdirectory + strFileName + ".ZIP";
try
{
FastZip fz = new FastZip();
fz.CreateEmptyDirectories = true;
fz.CreateZip(exportfile, inputdirectory, true, "");
fz = null;
try
{
//删除临时文件
Directory.Delete(inputdirectory, true);
}
catch
{
}
DownLoadUtils.ExportFile(exportfile, strFileName + ".ZIP", true);
}
catch (Exception ex)
{
throw;
}
}
#endregion
}
===解压===#region ===解压===
public class ZipUtils
{
public class UnzipException : ApplicationException
{
public UnzipException(string msg) : base(msg) { }
}
/**//// <summary>
/// 解压缩文件到指定目录
/// </summary>
/// <param name="filePath">表示压缩文件所在的路径</param>
/// <param name="extractFolder">表示解压缩后文件存放的目录</param>
public static void UnzipPack(string filePath, string extractFolder)
{
ZipConstants.DefaultCodePage = 936;//中文
ZipInputStream s = null;
try
{
s = new ZipInputStream(File.OpenRead(filePath));
//zip文件的入口类
ZipEntry theEntry;
//遍历压缩文件的所有入口
while (null != (theEntry = s.GetNextEntry()))
{
//设置解压文件目录名和文件名
//string directoryName = Path.GetDirectoryName ( extractFolder );
string directoryName = extractFolder;
//MessageBox.Show("directoryName:{0}",directoryName );
string fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
Directory.CreateDirectory(directoryName);
if (String.Empty != fileName)
{
//解压文件到指定文件夹
string path = directoryName + "/" + theEntry.Name;
FileInfo fileInfo = new FileInfo(path);
string str = path.Substring(0, path.Length - fileInfo.Name.Length - 1);
//MessageBox.Show(path );
if (!Directory.Exists(str)) Directory.CreateDirectory(str);
FileStream streamWriter = File.Create(path);
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();
}
}
}
catch
{
throw new UnzipException("ZipFileNotFound");
}
finally
{
s.Close();
}
}
}
#endregion
作者:蓝之风
出处:http://www.cnblogs.com/vaiyanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。