Start using the library with adding the reference to Telerik.Windows.Zip.
Files can be compressed by calling either Add or AddStream methods of ZipPackage class. The second method allows choosing between compression algorithms.
private static void TestCompress()
{
using (var compressedFile = File.Create(@"c:\temp\documents.zip"))
{
using (var zipPackage = ZipPackage.Create(compressedFile))
{
//zipPackage.Add(
// Directory.GetFiles(@"c:\temp").Where(
// item => new[] { ".doc", ".docx" }.Contains(Path.GetExtension(item))));
foreach (var file in Directory.GetFiles(@"c:\temp").Where(
item => new[] { ".doc", ".docx" }.Contains(Path.GetExtension(item))))
{
zipPackage.AddStream(
File.OpenRead(file),
Path.GetFileName(file),
ZipCompression.Deflate64,
DateTime.Now);
}
}
}
}
File extraction is performed through accessing ZipPackageEntries collection of the ZipPackage.
private static void TestDecompress()
{
const string SourceCompressedFile = @"C:\temp\documents.zip";
using (var sourceStream = File.OpenRead(SourceCompressedFile))
{
using (var zipPackage = ZipPackage.Open(sourceStream))
{
foreach (var zipPackageEntry in
zipPackage.ZipPackageEntries.OrderByDescending(item => item.FileNameInZip))
{
Console.WriteLine(zipPackageEntry.FileNameInZip);
using (var openInputStream = zipPackageEntry.OpenInputStream())
{
using (var outputStream =
File.Create(@"c:\temp\aa\" + zipPackageEntry.FileNameInZip))
{
openInputStream.CopyTo(outputStream);
}
}
}
}
}
}
The compression ratio is acceptable -- slightly below the WinZip's level and almost on par with the Windows' level.
Dec. 21, 2012: The following pair of methods shows how to work with strings. Note that Base64 conversion is used for handling zero bytes. Due to that do not expect getting any significant gain, or even any gain at all, on strings shorter than 1K.
private static string CompressString(string source)
{
using (var memoryStream =
new MemoryStream())
using (var outputStream =
new ZipOutputStream(memoryStream, ZipCompression.Default))
using (var writer =
new StreamWriter(outputStream))
{
writer.Write(source);
writer.Flush();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
private static string DecompressString(string source)
{
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(source)))
using (var inputStream =
new ZipInputStream(memoryStream))
using (var reader =
new StreamReader(inputStream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
No comments:
Post a Comment