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

编程入门 行业动态 更新时间:2024-10-20 07:39:56
本文介绍了如何将文件解压缩到 .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...

  • 解压到一个文件(什么目录?需要一些非常临时的位置...)
  • 读取文件内容
  • 删除文件.
  • 注意:文件的内容很小 - 比如 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 内存流?

    本文发布于:2023-11-05 08:06:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1560310.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:解压缩   如何将   内存   文件   NET

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!