Files
PepApi.Core/PepLib.Core/ZipHelper.cs
AJ Isaacs 61866df17e refactor(pep-lib): replace DotNetZip with System.IO.Compression and refactor readers
- Remove DotNetZip package from PepLib.Core.csproj
- Update DrawingReader, NestReader, and ZipHelper to use System.IO.Compression.ZipArchive
- Simplify stream handling and improve resource disposal
- Keep behavior consistent for loop/plate detection and extraction
2025-10-29 11:07:22 -04:00

85 lines
3.0 KiB
C#

using System.Collections.Generic;
using System.IO;
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;
}
}
}