-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZipUtils.cs
75 lines (66 loc) · 2.2 KB
/
ZipUtils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
namespace ZipDir;
using System.IO.Compression;
internal static class ZipUtils
{
/// <summary>
/// Magic number for a zip file. ReadOnlySpan is immutable and will not reallocate in this setting
/// See Framework Design Guidelines, 3rd Edition, sec 9.12 page 438
/// </summary>
private static ReadOnlySpan<byte> MagicNumberZip => [0x50, 0x4B, 0x03, 0x04];
/// <summary>
/// Is this a zip file? Check the extension
/// </summary>
internal static bool IsZipArchiveFilename(string filename) => filename.EndsWith(".zip", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Does this entry represent a nested zip file? Check the extension
/// </summary>
internal static bool IsZipArchiveFilename(ZipArchiveEntry entry) => IsZipArchiveFilename(entry.FullName);
/// <summary>
/// Build the full path to this entry
/// </summary>
internal static string EntryFilename(string containerName, ZipArchiveEntry entry)
{
if (entry.FullName.Contains('\\')) {
// path separator is '\', so replace with '/' for consistency
var s = entry.FullName.Replace('\\', '/');
return $"{containerName}/{s}";
}
return $"{containerName}/{entry.FullName}";
}
/// <summary>
/// Check the magic number of a physical file to see if it is a zip archive
/// </summary>
internal static bool IsZipArchiveContent(string filePath)
{
try {
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return CheckZipStream(fileStream);
}
catch (Exception) {
// some error in the zip file
return false;
}
}
/// <summary>
/// Check the magic number of a zip entry to see if it is a zip archive
/// </summary>
internal static bool IsZipArchiveContent(ZipArchiveEntry entry)
{
try {
using var entryStream = entry.Open();
return CheckZipStream(entryStream);
}
catch (Exception) {
// some error in the zip file
return false;
}
}
/// <summary>
/// Check if this open stream contains the magic bytes for a zip archive
/// </summary>
private static bool CheckZipStream(Stream stream)
{
Span<byte> contents = stackalloc byte[MagicNumberZip.Length]; // avoid heap allocation
return stream.Read(contents) >= MagicNumberZip.Length && contents.SequenceEqual(MagicNumberZip);
}
}