-
-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathZipHelper.cs
More file actions
87 lines (76 loc) · 3.18 KB
/
Copy pathZipHelper.cs
File metadata and controls
87 lines (76 loc) · 3.18 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.IO.Compression;
namespace System
{
public class ZipHelper
{
public static void ZipFile(string sourceFilePath, string destinationFilePathZip)
{
if (!File.Exists(sourceFilePath))
throw new FileNotFoundException($"Source file not found: {sourceFilePath}");
// Ensure destination directory exists
string destinationDir = Path.GetDirectoryName(destinationFilePathZip);
if (!string.IsNullOrEmpty(destinationDir))
Directory.CreateDirectory(destinationDir);
using (var zip = ZipStorer.Create(destinationFilePathZip, ""))
{
string entryName = Path.GetFileName(sourceFilePath);
zip.AddFile(ZipStorer.Compression.Deflate, sourceFilePath, entryName, "");
}
}
public static void ZipMemoryStream(string fileName, Stream streamSource, Stream streamDestination)
{
using (var zip = ZipStorer.Create(streamDestination, ""))
{
streamSource.Position = 0;
zip.AddStream(ZipStorer.Compression.Deflate, fileName, streamSource, DateTime.Now, "");
}
}
public static void ExtractFile(string sourceZipFilePath, string destinationFilePath)
{
if (!File.Exists(sourceZipFilePath))
throw new FileNotFoundException($"Source zip file not found: {sourceZipFilePath}");
// Ensure destination directory exists
string destinationDir = Path.GetDirectoryName(destinationFilePath);
if (!string.IsNullOrEmpty(destinationDir))
Directory.CreateDirectory(destinationDir);
using (ZipStorer zip = ZipStorer.Open(sourceZipFilePath, FileAccess.Read))
{
var files = zip.ReadCentralDir();
// Extract the first file found, or you could make this more specific
var firstFile = files.FirstOrDefault();
if (firstFile != null)
{
zip.ExtractFile(firstFile, destinationFilePath);
}
else
{
throw new InvalidOperationException("No files found in the zip archive.");
}
}
}
public static void ExtractToStream(Stream sourceStream, Stream destinationStream)
{
sourceStream.Position = 0;
using (ZipStorer zip = ZipStorer.Open(sourceStream, FileAccess.Read))
{
var files = zip.ReadCentralDir();
// Extract the first file found to the destination stream
var firstFile = files.FirstOrDefault();
if (firstFile != null)
{
zip.ExtractFile(firstFile, destinationStream);
destinationStream.Position = 0; // Reset position for reading
}
else
{
throw new InvalidOperationException("No files found in the zip archive.");
}
}
}
}
}