[英]Decompressing a zipfile into memory stream - C#
我已经编写了将zip文件的编码字符串存储到临时路径的代码,现在我想将编码的zipfile字符串存储到memorystream而不是临时路径。 有人可以帮助我如何读取流并将其作为字符串传递给ZipFile类...我正在使用DOTNETZIP库来解压密码遭到拒绝的文件。 请看下面我的代码。
string tempPath = Path.GetTempPath();
foreach (ActivityMimeAttachment a in attachments.Entities)
{
if (a.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
string strcontent = a.Body;
byte[] filecontent = Convert.FromBase64String(strcontent); // unpack the base-64 to a blob
File.WriteAllBytes(tempPath + a.FileName, filecontent); // Working code creates a zip file
string attachmentfile = tempPath + a.FileName;
using (ZipFile zip = new ZipFile(attachmentfile))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractWithPassword(tempPath, "password");
FileStream inFile;
byte[] binaryData;
string file = tempPath + entry.FileName;
inFile = new FileStream(file, FileMode.Open, FileAccess.Read);
binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0,
(int)inFile.Length);
inFile.Close();
您需要将文件内容转换为内存流( Stream filestream = new MemoryStream(filecontent)
),然后使用ZipFile.Read(fileStream)
。 然后使用StreamReader
将内容作为字符串取出。 因此,请尝试以下操作(请注意,未经测试):
string myString;
byte[] filecontent = Convert.FromBase64String(strcontent);
using (var filestream = new MemoryStream(filecontent))
{
using (ZipFile zip = ZipFile.Read(filestream))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
using (var ms = new MemoryStream())
{
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
var sr = new StreamReader(ms);
myString = sr.ReadToEnd();
}
...
如果结果应为base64字符串,请执行以下操作:
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
myString = Convert.ToBase64String(ms.ToArray());
您可能需要重置流位置,也可以不必重置,但这是一个好习惯。
现在,您可以将结果用作字符串,而不必先写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.