Last active
May 20, 2020 06:26
-
-
Save skenderbeu/0ec1a11813e3b7cc7aa740d90680a769 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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