首页 > IT基础架构 > 网络安全 > GZipStream类
下面是对字符串的压缩与解压缩。好像是加密解密。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Compression;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
//压缩字符串
private static string zipStrFunction(string zipstr)
{
byte[] btdata = System.Text.UTF8Encoding.UTF8.GetBytes(zipstr);
MemoryStream ms = new MemoryStream();
Stream s = new GZipStream(ms, CompressionMode.Compress);
s.Write(btdata, 0, btdata.Length);
s.Close();
byte[] compressedData = (byte[])ms.ToArray();
return System.Convert.ToBase64String(compressedData, 0, compressedData.Length);
}
//解压缩字符串
public static string unzipFunction(string unzipstr)
{
System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
byte[] writeData = new byte[4096];
byte[] bytData = System.Convert.FromBase64String(unzipstr);
int size = 0;
MemoryStream ms = new MemoryStream(bytData);
GZipStream zipstream = new GZipStream(ms, CompressionMode.Decompress);
while ((size = zipstream.Read(writeData, 0, writeData.Length))>0)
{
uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 0, size));
}
zipstream.Close();
return uncompressedString.ToString();
}
public static void Main(string[] args)
{
string zipStr, compressedStr,uncompressedStr;
Console.WriteLine("输入要压缩的字符串");
zipStr = Console.ReadLine();
compressedStr = zipStrFunction(zipStr);
Console.WriteLine("压缩后的:");
Console.WriteLine(compressedStr);
Console.WriteLine("解压:");
uncompressedStr = unzipFunction(compressedStr);
Console.WriteLine(uncompressedStr);
Console.ReadLine();
}
}
}
以上在.net2005上编译过可以直接运行。
[@more@]来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10606164/viewspace-928606/ ,如需转载,请注明出处,否则将追究法律责任。