-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReportExtractor.cs
More file actions
84 lines (71 loc) · 2.69 KB
/
Copy pathReportExtractor.cs
File metadata and controls
84 lines (71 loc) · 2.69 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
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DmarcTlsReportParser
{
public class ReportExtractor
{
private readonly string _inputDir;
private readonly string _outputDir;
public ReportExtractor(string inputDir, string outputDir)
{
_inputDir = inputDir;
_outputDir = outputDir;
}
public List<string> ExtractAll()
{
var newlyExtractedFiles = new List<string>();
foreach (var file in Directory.GetFiles(_inputDir))
{
try
{
var extension = Path.GetExtension(file).ToLowerInvariant();
if (extension == ".zip")
{
newlyExtractedFiles.AddRange(ExtractZip(file));
}
else if (extension == ".gz")
{
newlyExtractedFiles.Add(ExtractGzip(file));
}
File.Delete(file);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to extract {file}: {ex.Message}");
}
}
return newlyExtractedFiles;
}
private List<string> ExtractZip(string zipFilePath)
{
var extractedFiles = new List<string>();
var baseName = Path.GetFileNameWithoutExtension(zipFilePath);
var extractPath = Path.Combine(_outputDir, baseName);
Directory.CreateDirectory(extractPath);
using var archive = ZipFile.OpenRead(zipFilePath);
foreach (var entry in archive.Entries)
{
var fullPath = Path.Combine(extractPath, entry.Name);
entry.ExtractToFile(fullPath, overwrite: true);
Console.WriteLine($"Extracted ZIP: {entry.Name}");
extractedFiles.Add(fullPath);
}
return extractedFiles;
}
private string ExtractGzip(string gzipFilePath)
{
var baseName = Path.GetFileNameWithoutExtension(gzipFilePath); // e.g., report.xml or report.json
var extractPath = Path.Combine(_outputDir, baseName); // keeps .xml or .json
using var input = File.OpenRead(gzipFilePath);
using var output = File.Create(extractPath);
using var gzip = new GZipStream(input, CompressionMode.Decompress);
gzip.CopyTo(output);
Console.WriteLine($"Extracted GZ: {Path.GetFileName(extractPath)}");
return extractPath;
}
}
}