将zipfile解压缩到内存流中 - C#

时间:2016-01-20 12:46:58

标签: c#

我已编写代码将zip文件的编码字符串存储到temp路径中,现在我想将编码的zipfile字符串存储到memorystream而不是temp path。有人可以请帮助我如何读取流并将其作为字符串传递给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();

1 个答案:

答案 0 :(得分:0)

您希望将文件内容转换为内存流(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());

您可能需要或不必重置流位置,但这是一种很好的做法。

现在,您可以将结果用作字符串,而无需先写入文件。