問題描述
我有文件(來自第 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 內存流?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!