Files
BinaryObjectScanner/BinaryObjectScanner.FileType/PKZIP.cs

80 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.IO;
using BinaryObjectScanner.Interfaces;
using SharpCompress.Archives;
using SharpCompress.Archives.Zip;
namespace BinaryObjectScanner.FileType
{
/// <summary>
/// PKWARE ZIP archive and derivatives
/// </summary>
2023-03-09 15:07:35 -05:00
public class PKZIP : IExtractable
{
/// <inheritdoc/>
#if NET48
2023-03-09 17:16:39 -05:00
public string Extract(string file, bool includeDebug)
#else
public string? Extract(string file, bool includeDebug)
#endif
{
if (!File.Exists(file))
return null;
using (var fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
2023-03-09 17:16:39 -05:00
return Extract(fs, file, includeDebug);
}
}
/// <inheritdoc/>
#if NET48
2023-03-09 17:16:39 -05:00
public string Extract(Stream stream, string file, bool includeDebug)
#else
public string? Extract(Stream stream, string file, bool includeDebug)
#endif
{
2023-03-09 17:16:39 -05:00
try
2023-03-09 14:39:26 -05:00
{
2023-03-09 17:16:39 -05:00
// Create a temp output directory
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
using (ZipArchive zipFile = ZipArchive.Open(stream))
2023-03-09 14:39:26 -05:00
{
2023-03-09 17:16:39 -05:00
foreach (var entry in zipFile.Entries)
{
try
{
// If we have a directory, skip it
if (entry.IsDirectory)
continue;
2023-03-09 14:39:26 -05:00
2023-03-09 17:16:39 -05:00
string tempFile = Path.Combine(tempPath, entry.Key);
#if NET48
string directoryName = Path.GetDirectoryName(tempFile);
#else
string? directoryName = Path.GetDirectoryName(tempFile);
#endif
if (directoryName != null && !Directory.Exists(directoryName))
Directory.CreateDirectory(directoryName);
2023-03-09 17:16:39 -05:00
entry.WriteToFile(tempFile);
}
catch (Exception ex)
{
if (includeDebug) Console.WriteLine(ex);
}
}
2023-03-09 14:39:26 -05:00
}
2023-03-09 17:16:39 -05:00
return tempPath;
}
catch (Exception ex)
{
if (includeDebug) Console.WriteLine(ex);
return null;
}
}
}
}