首先我從this link下載了一個zip文件 解壓縮它並在第三個文件夾中添加了對dll的引用。
使用區間:
Using System.IO;
Using ICSharp.SharpZipLib.Zip;
代碼:
ZipOutputStream zos;
String strBaseDir;
protected void Page_Load(object sender, EventArgs e)
{
StartZip(Server.MapPath("directory name"), "filename");
}
protected void StartZip(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();
}
protected 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();
}
}
我得到這個代碼this link
我把它轉換成vb.net。下面是VB.NET用戶代碼:
進口部分:
Imports System.IO
Imports ICSharp.SharpZipLib.Zip
代碼:
Dim zos as ZipOutputStream
Dim strBaseDir as String
Public Sub btnBackUpDatabase_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBackUpDatabase.Click
StartZip(Server.MapPath("~/App_Data"), "Database")
End Sub
Protected Sub StartZip(ByVal strPath As String, ByVal strFileName As String)
Dim ms As IO.MemoryStream = Nothing
Response.ContentType = "application/octet-stream"
strFileName = HttpUtility.UrlEncode(strFileName).Replace("+"c, " "c)
Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName & ".zip")
ms = New IO.MemoryStream()
zos = New ZipOutputStream(ms)
strBaseDir = strPath & "\"
addZipEntry(strBaseDir)
zos.Finish()
zos.Close()
Response.Clear()
Response.BinaryWrite(ms.ToArray())
Response.[End]()
End Sub
Protected Sub addZipEntry(ByVal PathStr As String)
Dim di As New IO.DirectoryInfo(PathStr)
For Each item As IO.DirectoryInfo In di.GetDirectories()
addZipEntry(item.FullName)
Next
For Each item As IO.FileInfo In di.GetFiles()
Dim fs As IO.FileStream = IO.File.OpenRead(item.FullName)
Dim buffer As Byte() = New Byte(fs.Length - 1) {}
fs.Read(buffer, 0, buffer.Length)
Dim strEntryName As String = item.FullName.Replace(strBaseDir, "")
Dim entry As New ZipEntry(strEntryName)
zos.PutNextEntry(entry)
zos.Write(buffer, 0, buffer.Length)
fs.Close()
Next
End Sub
如果你知道在服務器中的文件夾的路徑,那麼你很可能壓縮的文件夾使用System.IO.Packaging.ZipPackage或第三方zip庫。然後,將該文件寫入響應流。 –
我無法找到system.io下的包裝。你能幫我一下嗎? – Vishal
您必須將該程序集添加到您的參考文獻中。這裏有一個例子:http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx –