/// <summary>
/// 壓縮文件夾
/// </summary>
/// <param name="tartgetFile">目標文件路徑</param>
/// <param name="sourceFile">源文件夾路徑</param>
private string Zip(string tartgetFile,string sourceFile)
{
using (ZipOutputStream ComStream = new ZipOutputStream(File.Create(tartgetFile)))
{
ComStream.SetLevel(6); //壓縮等級
if (!Directory.Exists(sourceFile))
return "不存在目錄";
//壓縮文件 有同名壓縮文件會自動替換
if (ZipFloder(sourceFile, ComStream, sourceFile))
{
return Download(tartgetFile);
}
}
return "失敗";
}
/// <summary>
/// 壓縮文件夾
/// </summary>
/// <param name="_OfloderPath"></param>
/// <param name="zos"></param>
/// <param name="_floderPath"></param>
private bool ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath)
{
try
{
foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos())
{
if (Directory.Exists(item.FullName))
{
ZipFloder(_OfloderPath, zos, item.FullName);
}
else if (File.Exists(item.FullName))//如果是文件
{
DirectoryInfo ODir = new DirectoryInfo(_OfloderPath);
string fullName2 = new FileInfo(item.FullName).FullName;
string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);//獲取相對目錄
FileStream fs = File.OpenRead(fullName2);
byte[] bts = new byte[fs.Length];
fs.Read(bts, 0, bts.Length);
ZipEntry ze = new ZipEntry(path);
zos.PutNextEntry(ze); //爲壓縮文件流提供一個容器
zos.Write(bts, 0, bts.Length); //寫入字節
fs.Dispose();
fs.Close();
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 文件下載
/// </summary>
/// <param name="fileRpath">文件路徑</param>
/// <returns></returns>
public string Download(string fileRpath)
{
try
{
HttpContext context = HttpContext.Current;
string name = Path.GetFileName(fileRpath);
FileStream files = new FileStream(fileRpath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] byteFile = null;
if (files.Length == 0)
byteFile = new byte[1];
else
byteFile = new byte[files.Length];
files.Read(byteFile, 0, byteFile.Length);
files.Close();
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(name, Encoding.UTF8));
//context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, Encoding.UTF8));
context.Response.ContentType = "application/octet-stream;charset=gbk";
context.Response.BinaryWrite(byteFile);
context.Response.End();
}
catch (Exception e)
{
return e.Message ;
}
return "成功" ;
}