Skip to content

Instantly share code, notes, and snippets.

@skenderbeu

skenderbeu/ZipUtil.cs

Last active May 20, 2020
Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using log4net;
public class ZipUtil : IZip
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ZipModule));
private string _zipFileName;
private List<string> _files;
public void SetZipFileName(string zipfileName)
{
_zipFileName = zipfileName;
}
public void SetFilesToZip(List<string> files)
{
_files = files;
}
public void CreateArchive()
{
try
{
if (!DoAnyFilesInFileListExist())
{
Log.DebugFormat("No Files to send");
return;
}
using (var zipFile = ZipFile.Open(_zipFileName, ZipArchiveMode.Create))
{
foreach (var file in _files)
{
AddToZip(zipFile, file);
}
}
}
catch (System.IO.DirectoryNotFoundException e)
{
Log.ErrorFormat("ZIP not created as directory doesn't exist: {0}.", e.Message);
}
catch (Exception e)
{
Log.ErrorFormat("ZIP not created: {0}.", e.Message);
}
}
private bool DoAnyFilesInFileListExist()
{
foreach (var fileName in _files)
{
if (File.Exists(fileName))
{
return true;
}
}
return false;
}
private void AddToZip(ZipArchive zipFile, string fileName)
{
if (!File.Exists(fileName))
{
Log.ErrorFormat("File not added to ZIP as doesn't exist: {0}.", fileName);
return;
}
Log.DebugFormat("File added to zip: {0}", fileName);
zipFile.CreateEntryFromFile(fileName, Path.GetFileName(fileName), CompressionLevel.Optimal);
File.Delete(fileName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.