前言:
这几天做关于文件下载和压缩的功能,觉得这些功能在大家的开发中肯定会用到,就把这些代码进行粘贴出来,为大家节省些时间。
代码如下:使用下面的代码之前需要下载一个压缩所需要的dll文件。
下载链接:压缩dll下载地址
/// <summary>
/// 将文件进行压缩,返回的是压缩后文件的名字
/// </summary>
/// <param name="preZipFilePath">压缩之前的文件路径</param>
/// <param name="LastZipFilePath">压缩之后的文件路径</param>
/// <param name="zipName">压缩文件的名字</param>
/// <param name="Level">压缩级别</param>
/// <param name="zipSize">压缩大小</param>
/// <returns></returns>
public static string ZipFile(string preZipFilePath, string lastZipFilePath,string zipName,int level,int zipSize)
{
//如果文件没有找到,则报错
if (!System.IO.File.Exists(preZipFilePath))
{
throw new System.IO.FileNotFoundException("指定要压缩的文件: " + preZipFilePath + " 不存在!");
}
//文件名称
string ZipFileName = string.IsNullOrEmpty(zipName) ? lastZipFilePath + "\\" + new FileInfo(preZipFilePath).Name.Substring(0, new FileInfo(preZipFilePath).Name.LastIndexOf('.')) + ".zip" : lastZipFilePath + "\\" +zipName+ ".zip";
//string ZipFileName = Guid.NewGuid().ToString();//压缩文件名
using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
using (System.IO.FileStream StreamToZip = new System.IO.FileStream(preZipFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
string fileName = preZipFilePath.Substring(preZipFilePath.LastIndexOf("\\") + 1);
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
//设置压缩级别
ZipStream.SetLevel(level);
//缓存大小
byte[] buffer = new byte[zipSize];
int sizeRead = 0;
try
{
do
{
sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, sizeRead);
}
while (sizeRead > 0);
}
catch (System.Exception ex)
{
throw ex;
}
StreamToZip.Close();
}
ZipStream.Finish();
ZipStream.Close();
}
ZipFile.Close();
}
return zipName;
}
代码经过实际操作,大家直接用就好。
结尾:
分享:耐得住寂寞,稳得住心性,每天进步一点点!