- MemoryQueue.zip
- bin
- NUnit
- nunit.framework.dll
- SharpZibLib
- ICSharpCode.SharpZipLib.dll
- SharpZipLib.dll
- Yakiloo.Api.Tests
- Yakiloo.Api
- Yakiloo.Interfaces
- Yakiloo.Logging.Tests
- Yakiloo.Logging
- Yakiloo.Queuing.Tests
- Yakiloo.Queuing
- Yakiloo.sln
|
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
namespace Yakiloo.Logging.Utilities
{
internal static class ZipUtilities
{
#region Zip Methods
/// <summary>
/// This Method performs the actual compression sequence using the ICSharpZipLib. File are
/// compressed in zip format and added to the zip archive after removing explicit folder
/// information
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
internal static string ZipFile(string fileToZip)
{
string zipFileName = string.Format("{0}.zip", fileToZip);
try
{
byte[] buffer = ReadFileToZip(fileToZip);
try
{
int fileNumber = 0;
// We have to check whether the file exists first and then append a number to the file seeing that we don't want to overwrite
// the file if it exists.
while (File.Exists(zipFileName))
{
zipFileName = string.Format("{0}_{1}.zip", fileToZip, fileNumber++);
}
using (ZipOutputStream outZip = new ZipOutputStream(File.Create(zipFileName)))
{
outZip.SetLevel(9); // 0 - store only to 9 - means best compression
ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1));
entry.DateTime = DateTime.UtcNow;
// Set Size and the CRC, because the information about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer. (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store the size and crc in the header.
entry.Size = buffer.Length;
Crc32 crc = new Crc32();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outZip.PutNextEntry(entry);
outZip.Write(buffer, 0, buffer.Length);
}
}
catch
{
File.Delete(zipFileName);
}
finally
{
// We set the zip creation equal to the original
if (File.Exists(zipFileName))
{
new FileInfo(zipFileName).CreationTime = new FileInfo(fileToZip).CreationTime;
File.Delete(fileToZip);
}
}
}
catch
{
// Unable to open exclusively
}
return zipFileName;
}
private static byte[] ReadFileToZip(string fileToZip)
{
byte[] buffer;
using (FileStream fileStream = File.Open(fileToZip, FileMode.Open, FileAccess.ReadWrite))
{
buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Close();
}
return buffer;
}
#endregion Zip Methods
}
}
|
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.