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.
Now, some of the files are .zip
files. Which means I can't process them. I need to unzip them first.
FTP has no concept of zip/unzipping - so I'll need to grab the zip file, unzip it, then process it.
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...
NOTE: The contents of the file are small - say 4k <-> 1000k.
Zip compression support is built in:
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 // ... } } } } }
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 }
You can use ZipArchiveEntry.Open
to get a stream.
This code assumes the zip archive has one text file.
using (FileStream fs = new FileStream(path, FileMode.Open)) using (ZipArchive zip = new ZipArchive(fs) ) { var entry = zip.Entries.First(); using (StreamReader sr = new StreamReader(entry.Open())) { Console.WriteLine(sr.ReadToEnd()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With