【发布时间】:2019-03-04 22:34:23
【问题描述】:
我不确定我做错了什么。我在获取byte[](即emailAttachment.Body)并将其传递给方法ExtractZipFile,将其转换为MemoryStream,然后解压缩,将其返回为KeyValuePair,然后写入文件后创建的文件使用FileStream。
但是,当我打开新创建的文件时,打开它们时出错。它们无法打开。
以下属于同一类
using Ionic.Zip;
var extractedFiles = ExtractZipFile(emailAttachment.Body);
foreach (KeyValuePair<string, MemoryStream> extractedFile in extractedFiles)
{
string FileName = extractedFile.Key;
using (FileStream file = new FileStream(CurrentFileSystem +
FileName.FileFullPath(),FileMode.Create, System.IO.FileAccess.Write))
{
byte[] bytes = new byte[extractedFile.Value.Length];
extractedFile.Value.Read(bytes, 0, (int) xtractedFile.Value.Length);
file.Write(bytes,0,bytes.Length);
extractedFile.Value.Close();
}
}
private Dictionary<string, MemoryStream> ExtractZipFile(byte[] messagePart)
{
Dictionary<string, MemoryStream> result = new Dictionary<string,MemoryStream>();
MemoryStream data = new MemoryStream(messagePart);
using (ZipFile zip = ZipFile.Read(data))
{
foreach (ZipEntry ent in zip)
{
MemoryStream memoryStream = new MemoryStream();
ent.Extract(memoryStream);
result.Add(ent.FileName,memoryStream);
}
}
return result;
}
我有什么遗漏吗?我不想只保存从MemoryStream 提取的文件的原始 zip 文件。
我做错了什么?
【问题讨论】:
-
This question's answer 似乎可以满足您的需求。很难说,因为你在那里添加了
Dictionary。 -
首先你应该处理所有一次性用品。
-
另外,不要做
CurrentFileSystem + FileName.FileFullPath(),总是做System.IO.Path.Combine(CurrentFileSystem, FileName.FileFullPath())。 -
确保在写入后将 MemoryStream 的位置设置回 0,因为我怀疑
ent.Extract会处理它 -
@KevinGosse 找到了它。旁注:
Stream有一个非常方便的CopyTo方法。或者更方便,直接将ZipEntry解压到新创建的FileStream。
标签: c# filestream zipfile memorystream