using Ah.Core.Compression.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ah.Core.Compression.Services
{
/// <summary>
/// Service for compressing and decompressing strings.
/// </summary>
public class CompressionService : ICompressionService
{
/// <summary>
/// Default compression service.
/// </summary>
public CompressionService()
{
}
/// <summary>
/// Decompresses byte array.
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public string Decompress(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
{
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
}
/// <summary>
/// Compresses provided string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public byte[] Compress(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
{
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
}
/// <summary>
/// Copies stream to stream.
/// </summary>
/// <param name="src"></param>
/// <param name="dest"></param>
private void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}
}
}
Small common class I've been using for compressing strings as needed.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.