如何将文件解压缩到.NET内存流? [英] How can I unzip a file to a .NET memory stream?

查看:156
本文介绍了如何将文件解压缩到.NET内存流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文件(来自第三方)正在通过FTP传输到我们服务器上的目录中。我下载了它们,甚至处理了x分钟。效果很好。

I have files (from 3rd parties) that are being FTP'd to a directory on our server. I download them and process them even 'x' minutes. Works great.

现在,有些文件是 .zip 文件。这意味着我无法处理它们。我需要先解压缩它们。

Now, some of the files are .zip files. Which means I can't process them. I need to unzip them first.

FTP没有zip / unzipping的概念-因此,我需要抓取zip文件,将其解压缩,然后对其进行处理。

FTP has no concept of zip/unzipping - so I'll need to grab the zip file, unzip it, then process it.

查看 MSDN zip API ,似乎没有办法解压缩到内存流?

Looking at the MSDN zip api, there seems to be no way i can unzip to a memory stream?

所以唯一的方法是这样做...

So is the only way to do this...


  1. 解压缩到文件(哪个目录?需要一些非常临时的位置...)

  2. 读取文件内容

  3. 删除文件。

注意:文件的内容很小-例如4k<-> 1000k。

NOTE: The contents of the file are small - say 4k <-> 1000k.

推荐答案

Zip压缩支持内置于其中:

Zip compression support is built in:

using System.IO;
using System.IO.Compression;
// ^^^ requires a reference to System.IO.Compression.dll
static class Program
{
    const string path = ...
    static void Main()
    {
        using(var file = File.OpenRead(path))
        using(var zip = new ZipArchive(file, ZipArchiveMode.Read))
        {
            foreach(var entry in zip.Entries)
            {
                using(var stream = entry.Open())
                {
                    // do whatever we want with stream
                    // ...
                }
            }
        }
    }
}

通常,您应该避免将其复制到另一个流中-仅按原样使用它,但是,如果您绝对需要它中MemoryStream ,您可以执行以下操作:

Normally you should avoid copying it into another stream - just use it "as is", however, if you absolutely need it in a MemoryStream, you could do:

using(var ms = new MemoryStream())
{
    stream.CopyTo(ms);
    ms.Position = 0; // rewind
    // do something with ms
}

这篇关于如何将文件解压缩到.NET内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆