Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active January 2, 2019 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/781231323366ded7387544f9e6f6003f to your computer and use it in GitHub Desktop.
Save poychang/781231323366ded7387544f9e6f6003f to your computer and use it in GitHub Desktop.
[將字串做 Gzip 壓縮/解壓縮] #dotnet
void Main()
{
var rawString = "Hi, my name is Poy Chang. I am currently conducting a project of enterprise app through Angular and .NET Core. As a developer and designer, I believe that keep learning and practicing is the most important thing. Reading, watching movies and traveling are also my favorites in my life.";
var zippedString = GZipCompressString(rawString);
Console.WriteLine($"壓縮結果:\r\n{zippedString}\r\n");
var unzipString = GZipDecompressString(zippedString);
Console.WriteLine($"解壓縮後:\r\n{unzipString}\r\n");
}
// 壓縮
public string GZipCompressString(string rawString)
{
using (var memoryStream = new MemoryStream())
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
var rawData = Encoding.UTF8.GetBytes(rawString);
gzipStream.Write(rawData, 0, rawData.Length);
gzipStream.Close();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
// 解壓縮
public string GZipDecompressString(string zippedString)
{
if (string.IsNullOrEmpty(zippedString))
{
return string.Empty;
}
else
{
var zippedData = Convert.FromBase64String(zippedString);
using (var memoryStream = new MemoryStream(zippedData))
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
using (var outBuffer = new MemoryStream())
{
var block = new byte[1024];
while (true)
{
var bytesRead = gzipStream.Read(block, 0, block.Length);
if (bytesRead <= 0) break;
outBuffer.Write(block, 0, bytesRead);
}
return Encoding.UTF8.GetString(outBuffer.ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment