您的位置:首页 > 编程语言 > ASP

Asp.net中文件的压缩与解压

2010-09-03 08:27 260 查看
  这里笔者为大家介绍在asp.net中使用文件的压缩与解压。在asp.net中使用压缩给大家带来的好处是显而易见的,首先是减小了服务器端文件存储的空间,其次下载时候下载的是压缩文件想必也会有效果吧,特别是比较大的文件。有的客户可能会很粗心上传的是文件,那么可以通过判断后缀名来判断文件,不是压缩文件,就可以压缩文件,在存储。

  这里笔者引用了一个DLL文件(ICSharpCode.SharpZipLib.dll)(包含在本文代码中),调用其中的函数,就可以对文件进行压缩及解压了。其中压缩笔者主要用到的函数是

/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileName">要压缩的所有文件(完全路径)</param>
/// <param name="name">压缩后文件路径</param>
/// <param name="Level">压缩级别</param>
public void ZipFileMain(string[] filenames, string name, int Level)
{
ZipOutputStream s = new ZipOutputStream(File.Create(name));
Crc32 crc = new Crc32();
//压缩级别
s.SetLevel(Level); // 0 - store only to 9 - means best compression
try
{
foreach (string file in filenames)
{
//打开压缩文件
FileStream fs = File.OpenRead(file);

byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);

//建立压缩实体
ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file));

//时间
entry.DateTime = DateTime.Now;

// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
//空间大小
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
catch
{
throw;
}
finally
{
s.Finish();
s.Close();
}

}


解压缩的主要代码

/// <summary>
/// 解压文件
/// </summary>
/// <param name="ZipPath">被解压的文件路径</param>
/// <param name="Path">解压后文件的路径</param>
public void UnZip(string ZipPath,string Path)
{
ZipInputStream s = new ZipInputStream(File.OpenRead(ZipPath));

ZipEntry theEntry;
try
{
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = System.IO.Path.GetFileName(theEntry.Name);

//生成解压目录
Directory.CreateDirectory(Path);

if (fileName != String.Empty)
{
//解压文件
FileStream streamWriter = File.Create(Path + fileName);

int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{

streamWriter.Close();
streamWriter.Dispose();
break;
}
}

streamWriter.Close();
streamWriter.Dispose();
}
}
}
catch
{
throw;
}
finally
{
s.Close();
s.Dispose();
}
}
}


那么我这里做了个简单的测试程序(点击下载



这里已知道要被压缩文件,这里只需填入要被压缩到的路径("D:\text\")解压路径一样。这里解压级别越大,压缩的就越厉害。

可以看测试小程序,将解压/压缩引入到你的项目中

好了,如果本文对你有作用请您留个言语,让笔者知道 ^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: