using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string longString = GetLongString(500);
string compressed = StringCompressor.CompressString(longString);
string uncompressed = StringCompressor.DecompressString(compressed);
Console.WriteLine("Original string length: {0}\r\nCompressed string length: {1}",
longString.Length, compressed.Length);
Console.ReadKey();
}
static string GetLongString(int len)
{
StringBuilder str = new StringBuilder();
Random rand = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < len; i++)
str.Append((char)rand.Next(65, 91));
return str.ToString();
}
}
public static class StringCompressor
{
public static string CompressString(string Input)
{
byte[] inputBytes = Encoding.ASCII.GetBytes(Input);
byte[] outputBytes;
using (MemoryStream outputStream = new MemoryStream())
{
using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, true))
{
compressionStream.Write(inputBytes, 0, inputBytes.Length);
}
outputBytes = new byte[outputStream.Length];
outputStream.Position = 0;
outputStream.Read(outputBytes, 0, outputBytes.Length);
}
return Convert.ToBase64String(outputBytes);
}
public static string DecompressString(string Input)
{
byte[] inputBytes = Convert.FromBase64String(Input);
byte[] outputBytes;
using (MemoryStream inputStream = new MemoryStream())
{
inputStream.Write(inputBytes, 0, inputBytes.Length);
inputStream.Position = 0;
using (GZipStream outputStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
outputBytes = GetAllBytes(outputStream);
}
}
return Encoding.ASCII.GetString(outputBytes);
}
static byte[] GetAllBytes(Stream stream)
{
const int buffer_size = 1024;
byte[] buffer = new byte[buffer_size];
List<byte> streamBytes = new List<byte>();
if (stream.CanSeek)
stream.Position = 0;
int bytesRead = 0;
do
{
bytesRead = stream.Read(buffer, 0, buffer_size);
if (bytesRead > 0)
streamBytes.AddRange(buffer.Take(bytesRead));
} while (bytesRead > 0);
return streamBytes.ToArray();
}
}
}
|