压缩
public static void CreateZipFileTTT(string folderToZip, string zipedFile)
{
bool result = false;
if (!Directory.Exists(folderToZip))
return;
ZipOutputStream zipStream = new ZipOutputStream(System.IO.File.Create(zipedFile));
zipStream.SetLevel(6);
result = ZipDirectory(folderToZip, zipStream, "");
zipStream.Finish();
zipStream.Close();
return;
}
private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
{
bool result = true;
string[] folders, files;
ZipEntry ent = null;
FileStream fs = null;
//Crc32 crc = new Crc32();
try
{
ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
zipStream.PutNextEntry(ent);
zipStream.Flush();
files = Directory.GetFiles(folderToZip);
foreach (string file in files)
{
fs = System.IO.File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
ent.DateTime = DateTime.Now;
ent.Size = fs.Length;
fs.Close();
zipStream.PutNextEntry(ent);
zipStream.Write(buffer, 0, buffer.Length);
}
}
catch
{
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect(1);
}
folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
if (!ZipDirectory(folder, zipStream, Path.GetFileName(folderToZip)))
return false;
return result;
}
下载
public void DownloadFile(string strFilePath)
{
FileInfo fileInfo = new FileInfo(strFilePath);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileInfo.Name));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/x-bittorrent";
Response.WriteFile(fileInfo.FullName);
Response.End();
}
调用:例
public List<tb_Str> tb_sArray = new List<tb_Str>();
public void DownloadFileTT()
{
string DownLoad = @"D:/DownFile"; //例:文件夹
CreateZipFileTTT(DownLoad, DownLoad + "/zip.zip");
DownloadFile(DownLoad + "/zip.zip");
//tb_sArray对象存储的是D:/DownFile下所有的文件夹路径.
//删除 "D:/DownFile" 文件夹中的所有文件夹:注 此处DownFile下都是文件夹 有文件不可直接下面循环删除
foreach (var item in tb_sArray)
{
Directory.Delete(item.Str, true);
}
//删除压缩包
System.IO.File.Delete(DownLoad + "/zip.zip");
}
类
public class tb_Str
{
public string Str { set; get; }
}