[英]ZipArchive returning empty files c#
所以我已經實現了壓縮文件,但現在我有另一個問題,zip文件夾包含空文件。 壓縮文件的大小為0字節。
這就是我壓縮文件的方式
try
{
var outPutDirectory = AppDomain.CurrentDomain.BaseDirectory;
string logoimage = Path.Combine(outPutDirectory, "images\\error.png");
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=pauls_chapel_audio.zip");
using (MemoryStream ms = new MemoryStream())
{
// create new ZIP archive within prepared MemoryStream
using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var demoFile = zip.CreateEntry(logoimage);
// add some files to ZIP archive
}
ms.WriteTo(HttpContext.Current.Response.OutputStream);
}
return true;
}
另一個問題是壓縮文件夾的路徑與圖像的路徑相同。 所以它就像
ZippFolder/A/B/C/image...
我只需要
ZipFolder/content
var demoFile = zip.CreateEntry(logoimage);
這將在ZIP文件中創建一個名為logoimage
(即/A/B/C/images/error.png
或其他任何路徑)。
但是你從不寫那個條目,所以它是空的。 此外,如果您想要一個不同的路徑,您應該在那里指定它:
var demoFile = zip.CreateEntry("content\\error.png");
using (StreamWriter writer = new StreamWriter(demoFile.Open()))
using (StreamReader reader = new StreamReader(logoimage))
{
writer.Write(reader.ReadToEnd());
}
或者,您也可以完全跳過StreamWriter
,直接寫入流:
using (Stream stream = demoFile.Open())
using (StreamReader reader = new StreamReader(logoimage))
{
reader.BaseStream.CopyTo(stream);
}
順便說一句。 您可以跳過要在其中首先編寫zip文件的外部MemoryStream
,然后將該流寫入OutputStream
。 相反,您可以直接寫入該流。 只需將其傳遞給ZipFile
構造函數:
Stream output = HttpContext.Current.Response.OutputStream;
using (ZipArchive zip = new ZipArchive(output, ZipArchiveMode.Create, true))
{
…
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.