在做项目的时候经常会用到文件的要所或者是解压缩,这里提供一个文件的压缩操作的类
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架