在.net1.1中我们要实现压缩这一功能,一般都是用opensource的SharpZipLib或者调用J#类库。
现在在.net2.0中增加了压缩功能,名字空间为usingSystem.IO.Compression;
以下是使用示例:
压缩字符串
复制代码 代码如下:
publicstaticstringZipString(stringunCompressedString)
{
byte[]bytData=System.Text.Encoding.UTF8.GetBytes(unCompressedString);
MemoryStreamms=newMemoryStream();
Streams=newGZipStream(ms,CompressionMode.Compress);
s.Write(bytData,0,bytData.Length);
s.Close();
byte[]compressedData=(byte[])ms.ToArray();
returnSystem.Convert.ToBase64String(compressedData,0,compressedData.Length);
}
解压缩字符串
复制代码 代码如下:
publicstaticstringUnzipString(stringunCompressedString)
{
System.Text.StringBuilderuncompressedString=newSystem.Text.StringBuilder();
byte[]writeData=newbyte[4096];
byte[]bytData=System.Convert.FromBase64String(unCompressedString);
inttotalLength=0;
intsize=0;
Streams=newGZipStream(newMemoryStream(bytData),CompressionMode.Decompress);
while(true)
{
size=s.Read(writeData,0,writeData.Length);
if(size>0)
{
totalLength+=size;
uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData,0,size));
}
else
{
break;
}
}
s.Close();
returnuncompressedString.ToString();
}
压缩文件
复制代码 代码如下:
publicstaticboolAddZip(stringsrcFilename,stringzipFileName)
{
if(!File.Exists(srcFilename))
returnfalse;
boolresult;
FileStreamfs=null,output=null;
GZipStreamzipStream=null;
try
{
fs=newFileStream(srcFilename,FileMode.Open,FileAccess.Read);
byte[]buffer=newbyte[fs.Length];
fs.Read(buffer,0,buffer.Length);
fs.Close();
if(!File.Exists(zipFileName))
{
output=File.Create(zipFileName);
zipStream=newGZipStream(output,CompressionMode.Compress);
zipStream.Write(buffer,0,buffer.Length);
result=true;
}
else
{
result=false;
}
}
catch(Exception)
{
result=false;
}
finally
{
if(zipStream!=null)
{
zipStream.Flush();
zipStream.Close();
}
}
returnresult;
}