69 lines
2.7 KiB
C#
69 lines
2.7 KiB
C#
using System;
|
|
using System.Formats.Tar;
|
|
using FileCompression.Interfaces;
|
|
using FileCompression.Utils;
|
|
|
|
namespace FileCompression.Services.Strategies;
|
|
|
|
public class TarGzStrategy : ICompressionStrategy
|
|
{
|
|
public void CompressFile(string sourcePath, string destinationPath, string basePath)
|
|
{
|
|
Console.WriteLine($"Compressing {sourcePath} to {destinationPath} using tar and gzip.");
|
|
string tempPath = Path.GetTempFileName();
|
|
using (var tempStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write))
|
|
using (var tempWriter = new TarWriter(tempStream, TarEntryFormat.Pax))
|
|
{
|
|
// Copy existing entries to temp file
|
|
if (File.Exists(destinationPath))
|
|
{
|
|
using (var originalStream = new FileStream(destinationPath, FileMode.Open, FileAccess.Read))
|
|
using (var tarReader = new TarReader(originalStream, leaveOpen: false))
|
|
{
|
|
TarEntry? entry;
|
|
while ((entry = tarReader.GetNextEntry()) is not null)
|
|
{
|
|
tempWriter.WriteEntry(entry);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Add new entry
|
|
string entryName = ArchiveUtils.EntryFromPath(sourcePath.AsSpan(basePath.Length));
|
|
tempWriter.WriteEntry(sourcePath, entryName);
|
|
}
|
|
|
|
File.Copy(tempPath, destinationPath, overwrite: true);
|
|
File.Delete(tempPath);
|
|
|
|
}
|
|
|
|
public void CompressDirectory(string sourcePath, string destinationPath, string basePath)
|
|
{
|
|
Console.WriteLine($"Compressing {sourcePath} to {destinationPath} using tar and gzip.");
|
|
string tempPath = Path.GetTempFileName();
|
|
using (var tempStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write))
|
|
using (var tempWriter = new TarWriter(tempStream, TarEntryFormat.Pax))
|
|
{
|
|
// Copy existing entries to temp file
|
|
if (File.Exists(destinationPath))
|
|
{
|
|
using (var originalStream = new FileStream(destinationPath, FileMode.Open, FileAccess.Read))
|
|
using (var tarReader = new TarReader(originalStream, leaveOpen: false))
|
|
{
|
|
TarEntry? entry;
|
|
while ((entry = tarReader.GetNextEntry()) is not null)
|
|
{
|
|
tempWriter.WriteEntry(entry);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Add new entry
|
|
string entryName = ArchiveUtils.EntryFromPath(sourcePath.AsSpan(basePath.Length), appendPathSeparator: true);
|
|
tempWriter.WriteEntry(sourcePath, entryName);
|
|
}
|
|
|
|
}
|
|
}
|