当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

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

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

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

  1  /// <summary>

  2         /// 压缩文件

  3         /// </summary>

  4         /// <param name="fileName">要压缩的所有文件(完全路径)</param>

  5         /// <param name="name">压缩后文件路径</param>

  6         /// <param name="Level">压缩级别</param>

  7          public void ZipFileMain(string[] filenames, string name, int Level)

  8         {

  9             ZipOutputStream s = new ZipOutputStream(File.Create(name));

  10             Crc32 crc = new Crc32();

  11             //压缩级别

  12             s.SetLevel(Level); // 0 - store only to 9 - means best compression

  13             try

  14             {

  15                 foreach (string file in filenames)

  16                 {

  17                     //打开压缩文件

  18                     FileStream fs = File.OpenRead(file);

  19

  20                     byte[] buffer = new byte[fs.Length];

  21                     fs.Read(buffer, 0, buffer.Length);

  22

  23                     //建立压缩实体

  24                     ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file));

  25

  26                     //时间

  27                     entry.DateTime = DateTime.Now;

  28

  29                     // set Size and the crc, because the information

  30                     // about the size and crc should be stored in the header

  31                     // if it is not set it is automatically written in the footer.

  32                     // (in this case size == crc == -1 in the header)

  33                     // Some ZIP programs have problems with zip files that don't store

  34                     // the size and crc in the header.

  35                     //空间大小

  36                     entry.Size = fs.Length;

  37                     fs.Close();

  38                     crc.Reset();

  39                     crc.Update(buffer);

  40                     entry.Crc = crc.Value;

  41                     s.PutNextEntry(entry);

  42                     s.Write(buffer, 0, buffer.Length);

  43                 }

  44             }

  45             catch

  46             {

  47                 throw;

  48             }

  49             finally

  50             {

  51                 s.Finish();

  52                 s.Close();

  53             }

  54

  55         }

相关内容
赞助商链接