当前位置: 移动技术网 > IT编程>开发语言>.net > .NET 2.0 的压缩功能代码

.NET 2.0 的压缩功能代码

2018年04月25日  | 移动技术网IT编程  | 我要评论

但愿人长久苏轼,用excel制作表格,房价网上海

在.net 1.1中我们要实现压缩这一功能,一般都是用open source的sharpziplib 或者调用j#类库。
现在在.net 2.0中增加了压缩功能,名字空间为 using system.io.compression;

以下是使用示例:

压缩字符串
复制代码 代码如下:

public static string zipstring(string uncompressedstring) 


byte[] bytdata = system.text.encoding.utf8.getbytes(uncompressedstring); 
memorystream ms = new memorystream(); 
stream s = new gzipstream(ms, compressionmode.compress); 
s.write(bytdata, 0, bytdata.length); 
s.close(); 
byte[] compresseddata = (byte[])ms.toarray();  
return system.convert.tobase64string(compresseddata, 0, compresseddata.length); 



解压缩字符串
复制代码 代码如下:

public static string unzipstring(string uncompressedstring) 

system.text.stringbuilder uncompressedstring = new system.text.stringbuilder(); 
byte[] writedata = new byte[4096]; 

byte[] bytdata = system.convert.frombase64string(uncompressedstring); 
int totallength = 0; 
int size = 0; 

stream s = new gzipstream(new memorystream(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(); 
return uncompressedstring.tostring(); 


压缩文件
复制代码 代码如下:

public static bool addzip(string srcfilename, string zipfilename) 

if (!file.exists(srcfilename)) 
return false; 
bool result; 
filestream fs = null, output = null; 
gzipstream zipstream = null; 
try 

fs = new filestream(srcfilename, filemode.open, fileaccess.read);  
byte[] buffer = new byte[fs.length]; 
fs.read(buffer, 0, buffer.length); 
fs.close(); 
if (!file.exists(zipfilename)) 

output = file.create(zipfilename); 
zipstream = new gzipstream(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(); 


return result; 
}  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网