Files
PepApi.Core/PepLib.Core/ZipHelper.cs
AJ 7c5b4ded5f chore(PepLib.Core): remove unused using directives and clean up formatting
Remove unnecessary System, System.Collections.Generic, System.IO, and
System.Linq using directives that were flagged by IDE analyzers. Also
includes minor whitespace and code style normalization.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 07:52:17 -05:00

83 lines
3.0 KiB
C#

using System.IO.Compression;
using System.Text.RegularExpressions;
namespace PepLib
{
public static class ZipHelper
{
/// <summary>
/// Returns the files that match the specified pattern.
/// </summary>
/// <param name="file">Input zip file.</param>
/// <param name="pattern">Pattern to match.</param>
/// <param name="names">Names of the files that match the pattern.</param>
/// <param name="streams">Data of the files that match the pattern.</param>
/// <returns></returns>
public static int ExtractByPattern(string file, string pattern, out string[] names, out Stream[] streams)
{
var nameList = new List<string>();
var streamList = new List<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 (!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;
}
/// <summary>
/// Returns the first file found that matches the specified file extension.
/// </summary>
/// <param name="file">Input zip file.</param>
/// <param name="extension">Extension to match.</param>
/// <param name="name">The name of the file that matches the file extension.</param>
/// <param name="stream">The data of the file that matches the file extension.</param>
/// <returns></returns>
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;
}
}
}