如何将文件解压缩到 .NET 内存流?

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

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

问题描述

我有文件(来自第 3 方)正在通过 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 文件,解压缩,然后处理它.

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压缩支持内置:

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 内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何将文件解压缩到 .NET 内存流?

基础教程推荐