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 内存流?
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01