.NET 2.0 的压缩功能代码
时间:2023-07-14 05:25:22
在.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;
}
标签:.NET,2.0,的压缩功能代码
0
投稿
猜你喜欢
Python3分析处理声音数据的例子
2021-04-21 03:23:26
一些你可能不熟悉的JS知识点总结
2024-04-17 09:46:24
Python logging设置和logger解析
2021-07-15 22:12:52
Python原始字符串(raw strings)用法实例
2021-05-04 18:29:27
MySQL慢查询日志的作用和开启
2024-01-21 20:23:33
Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)
2022-05-03 10:35:40
如何使用Python抓取网页tag操作
2023-11-11 12:15:24
利用Python实现Windows下的鼠标键盘模拟的实例代码
2023-06-22 04:37:31
Tensorflow tf.dynamic_partition矩阵拆分示例(Python3)
2021-07-10 10:35:25
页面制作中要注意的编码问题
2008-08-11 12:43:00
pytorch中的squeeze函数、cat函数使用
2022-03-27 14:32:24
TensorFlow通过文件名/文件夹名获取标签,并加入队列的实现
2023-02-14 17:08:47
Firefox Bug: inline/inline-block的间隙
2009-11-03 13:20:00
JavaScript实现动态生成表格
2024-04-10 10:54:05
对于任意的XML的遍历
2008-09-05 17:11:00
IE不支持border-spacing的解决办法
2009-04-28 13:11:00
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
2023-04-21 19:20:50
MySQL里面的子查询实例
2024-01-14 20:43:17
Go语言map字典用法实例分析
2024-04-26 17:29:18
Python检测和防御DOS攻击的最简单方法
2022-04-12 17:23:19