ICSharpCode.SharpZipLib.Zip 压缩文件

public class ZipFileHelper
{
List<string> urls = new List<string>();
void Director(string dir)
{
DirectoryInfo d = new DirectoryInfo(dir);
FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
foreach (FileSystemInfo fsinfo in fsinfos)
{
if (fsinfo is DirectoryInfo) //判断是否为文件夹
{
Director(fsinfo.FullName);//递归调用
}
else
{
// Console.WriteLine(fsinfo.FullName);//输出文件的全部路径
urls.Add(fsinfo.FullName);
} }
}
///<summary>
/// 创建ZIP文件
///</summary>
public void CreateZipFile(string dir, string sTempFile, string sPassWord)
{
try
{
Director(dir);
var files = urls.ToArray();
using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
{
s.SetLevel(); // 压缩级别 0-9
if (sPassWord != "")
{
s.Password = sPassWord; //Zip压缩文件密码
} byte[] buffer = new byte[]; //缓冲区大小 foreach (string file in files)
{
if (!string.IsNullOrEmpty(file))
{
if (File.Exists(file))
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
else
{
//logger.Error("文件:" + file + "不存在。");
}
}
} s.Finish();
s.Close();
}
}
catch (Exception ex)
{
//logger.Error("压缩文件时异常!");
//logger.Error("异常描述:\t" + ex.Message);
//logger.Error("异常方法:\t" + ex.TargetSite);
//logger.Error("异常堆栈:\t" + ex.StackTrace);
}
} /// <summary>
///
/// </summary>
/// <param name="files">放入ZIP的文件路劲(含文件名)</param>
/// <param name="sTempFile">创建的ZIP文件路劲(含文件名)</param>
/// <param name="sPassWord">ZIP文件密码</param>
/// <param name="folderNames">存放到ZIP中的文件夹名,空代表放在*目录</param>
public void CreateZipFileMutilFolder(string[] files, string sTempFile, string sPassWord, string[] folderNames)
{
try
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
{
s.SetLevel(); // 压缩级别 0-9
if (sPassWord != "")
{
s.Password = sPassWord; //Zip压缩文件密码
} byte[] buffer = new byte[]; //缓冲区大小 int i = ;
foreach (string file in files)
{
if (!string.IsNullOrEmpty(file))
{
if (File.Exists(file))
{
ZipEntry entry = new ZipEntry((string.IsNullOrEmpty(folderNames[i]) ? "" : (folderNames[i] + "\\")) + Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
else
{
//logger.Error("文件:" + file + "不存在。");
}
} i++;
} s.Finish();
s.Close();
}
}
catch (Exception ex)
{
//logger.Error("压缩文件时异常!");
//logger.Error("异常描述:\t" + ex.Message);
//logger.Error("异常方法:\t" + ex.TargetSite);
//logger.Error("异常堆栈:\t" + ex.StackTrace);
}
}
}
上一篇:分布式存储Ceph的几种安装方法,源码,apt-get,deploy工具,Ubuntu CentOS


下一篇:Android 利用摄像头指尖测试心率