日期:2014-05-19  浏览次数:20587 次

怎么用C#压缩指定文件夹下的所有文件啊
定时压缩文件做备份用,
大家帮帮忙把,

------解决方案--------------------
public string ServerDir=@ "d:\ ";

ZipOutputStream zos=null;
string strBaseDir= " ";
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
//dlZipDir(@ "d:\a ", "tanjun ");
ZipFile(@ "D:\x ",@ "d:\a.zip ");
}
void dlZipDir(string strPath,string strFileName)
{
MemoryStream ms =null;
Response.ContentType = "application/octet-stream ";
strFileName=HttpUtility.UrlEncode(strFileName).Replace( '+ ', ' ');
Response.AddHeader( "Content-Disposition ", "attachment; filename= " + strFileName+ ".zip ");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir=strPath+ "\\ ";
addZipEntry(strBaseDir);
zos.Finish();

zos.Close();
Response.Clear();
Response.BinaryWrite(ms.ToArray());
Response.End();



}

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);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}



public void ZipFile(string strFile, string strZip)
{
if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
strFile += Path.DirectorySeparatorChar;
if(File.Exists(strZip)) File.Delete(strZip);
ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
s.SetLevel(6); // 0 - store only to 9 - means best compression
zip(strFile, s);
s.Finish();
s.Close();
}
private void zip(string strFile, ZipOutputStream s)
{
if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
strFile += Path.DirectorySeparatorChar;
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strFile);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
zip(file,s);
}
else
{
//打开压缩文件
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string tempfile = file.Substring(file.IndexOf(@ "\ ")+1);
ZipEntry entry = new ZipEntry(tempfile);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;

fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}

}