How can I unzip a file to a .NET memory stream?(如何将文件解压缩到 .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 内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将文件解压缩到 .NET 内存流?


基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01