Last active
January 2, 2019 08:36
-
-
Save poychang/781231323366ded7387544f9e6f6003f to your computer and use it in GitHub Desktop.
[將字串做 Gzip 壓縮/解壓縮] #dotnet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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