|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SevenZip;
namespace CBR.Core.Helpers
{
public class ZipHelper
{
#region ----------------SINGLETON----------------
public static readonly ZipHelper Instance = new ZipHelper();
/// <summary>
/// Private constructor for singleton pattern
/// </summary>
private ZipHelper()
{
//be sure 7zip is initialized
SevenZipExtractor.SetLibraryPath(Path.Combine(DirectoryHelper.DependenciesPath, "7z.dll"));
}
#endregion
public SevenZipExtractor GetExtractor( string filePath )
{
SevenZipExtractor temp = null;
try
{
temp = new SevenZipExtractor(filePath);
}
catch (Exception err)
{
ExceptionHelper.Manage("ZipHelper:GetExtractor", err);
ReleaseExtractor(temp);
}
return temp;
}
public void ReleaseExtractor(SevenZipExtractor extractor)
{
if (extractor != null)
{
extractor.Dispose();
extractor = null;
}
}
#region ----------------FOLDERS----------------
public bool CompressFolder(string outputFileName, string inputFolder, out int resultCount)
{
SevenZip.SevenZipCompressor cp = null;
try
{
cp = new SevenZip.SevenZipCompressor();
cp.ArchiveFormat = SevenZip.OutArchiveFormat.Zip;
string[] outputFiles = new DirectoryInfo(inputFolder).GetFiles("*.*").Select(p => p.FullName).ToArray();
using (FileStream fs = new FileStream(outputFileName, FileMode.Create))
{
cp.CompressFiles(fs, outputFiles);
}
resultCount = outputFiles.Count();
return true;
}
catch (Exception err)
{
ExceptionHelper.Manage("ZipHelper:CompressFolder", err);
resultCount = 0;
return false;
}
finally
{
cp = null;
}
}
public bool UncompressToFolder(string inputFile, string outputFolder, out int resultCount)
{
SevenZipExtractor temp = null;
try
{
temp = GetExtractor(inputFile);
DirectoryHelper.Check(outputFolder);
temp.PreserveDirectoryStructure = false;
temp.ExtractArchive(outputFolder);
resultCount = temp.ArchiveFileData.Count;
return true;
}
catch (Exception err)
{
ExceptionHelper.Manage("ZipHelper:UncompressToFolder", err);
resultCount = 0;
return false;
}
finally
{
ReleaseExtractor(temp);
}
}
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
WPF and MVVM fan, I practice C # in all its forms from the beginning of the NET Framework without mentioning C ++ / MFC and other software packages such as databases, ASP, WCF, Web & Windows services, Application, and now Core and UWP.
In my wasted hours, I am guilty of having fathered C.B.R. and its cousins C.B.R. for WinRT and UWP on the Windows store.
But apart from that, I am a great handyman ... the house, a rocket stove to heat the jacuzzi and the last one: a wood oven for pizza, bread, and everything that goes inside
https://guillaumewaser.wordpress.com/
https://fouretcompagnie.wordpress.com/