moh*_*317 4 c# compression asp.net
所以我已经实现了压缩文件,但现在我有另一个问题,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;
}
Run Code Online (Sandbox Code Playgroud)
另一个问题是压缩文件夹的路径与图像的路径相同.所以它就像
ZippFolder/A/B/C/image...
Run Code Online (Sandbox Code Playgroud)
我只需要
ZipFolder/content
Run Code Online (Sandbox Code Playgroud)
var demoFile = zip.CreateEntry(logoimage);
Run Code Online (Sandbox Code Playgroud)
这将在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());
}
Run Code Online (Sandbox Code Playgroud)
或者,您也可以StreamWriter完全跳过,只需直接写入流:
using (Stream stream = demoFile.Open())
using (StreamReader reader = new StreamReader(logoimage))
{
reader.BaseStream.CopyTo(stream);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句.您可以先跳过MemoryStream要写入zip文件的外部,然后将该流写入OutputStream.相反,您可以直接写入该流.只需将其传递给ZipFile构造函数:
Stream output = HttpContext.Current.Response.OutputStream;
using (ZipArchive zip = new ZipArchive(output, ZipArchiveMode.Create, true))
{
…
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1753 次 |
| 最近记录: |