using System.IO.Compression;
using System.Text.RegularExpressions;
namespace PepLib
{
public static class ZipHelper
{
///
/// Returns the files that match the specified pattern.
///
/// Input zip file.
/// Pattern to match.
/// Names of the files that match the pattern.
/// Data of the files that match the pattern.
///
public static int ExtractByPattern(string file, string pattern, out string[] names, out Stream[] streams)
{
var nameList = new List();
var streamList = new List();
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
using (var zip = new ZipArchive(fileStream, ZipArchiveMode.Read))
{
foreach (var entry in zip.Entries)
{
if (!Regex.IsMatch(entry.FullName, pattern))
continue;
nameList.Add(entry.FullName);
var memstream = new MemoryStream();
using var entryStream = entry.Open();
entryStream.CopyTo(memstream);
memstream.Seek(0, SeekOrigin.Begin);
streamList.Add(memstream);
}
}
names = nameList.ToArray();
streams = streamList.ToArray();
return streams.Length;
}
///
/// Returns the first file found that matches the specified file extension.
///
/// Input zip file.
/// Extension to match.
/// The name of the file that matches the file extension.
/// The data of the file that matches the file extension.
///
public static bool ExtractByExtension(string file, string extension, out string name, out Stream stream)
{
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
using (var zip = new ZipArchive(fileStream, ZipArchiveMode.Read))
{
foreach (var entry in zip.Entries)
{
if (Path.GetExtension(entry.FullName) != extension)
continue;
var memstream = new MemoryStream();
using var entryStream = entry.Open();
entryStream.CopyTo(memstream);
memstream.Seek(0, SeekOrigin.Begin);
stream = memstream;
name = entry.FullName;
return true;
}
}
stream = null;
name = null;
return false;
}
}
}