ASP.NET上传文件或文件夹并进行压缩及解压

ASP.NET上传文件用FileUpLoad就可以,但是对文件夹的操作却不能用FileUpLoad来实现。

下面这个示例便是使用ASP.NET来实现上传文件夹并对文件夹进行压缩以及解压。

ASP.NET页面设计:TextBox和Button按钮。

TextBox中需要自己受到输入文件夹的路径(包含文件夹),通过Button实现选择文件夹的问题还没有解决,暂时只能手动输入。

两种方法:生成rar和zip。

1.生成rar

 1 using Microsoft.Win32;
 2 using System.Diagnostics;
 3 protected void Button1Click(object sender, EventArgs e)
 4     {
 5         RAR(@"E:\95413594531\GIS", "tmptest", @"E:\95413594531\");
 6     }
 7     ///
 8    /// 压缩文件
 9    ///
10    /// 需要压缩的文件夹或者单个文件
11    /// 生成压缩文件的文件名
12    /// 生成压缩文件保存路径
13    ///
14     protected bool RAR(string DFilePath, string DRARName,string DRARPath)
15     {
16         String therar;
17         RegistryKey theReg;
18         Object theObj;
19         String theInfo;
20         ProcessStartInfo theStartInfo;
21         Process theProcess;
22         try
23         {
24             theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"); //注:未在注册表的根路径找到此路径
25             theObj = theReg.GetValue("");
26             therar = theObj.ToString();
27             theReg.Close();
28             therar = therar.Substring(1, therar.Length - 7);
29             theInfo = " a    " + " " + DRARName + "  " + DFilePath +" -ep1"; //命令 + 压缩后文件名 + 被压缩的文件或者路径
30             theStartInfo = new ProcessStartInfo();
31             theStartInfo.FileName = therar;
32             theStartInfo.Arguments = theInfo;
33             theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
34             theStartInfo.WorkingDirectory = DRARPath ; //RaR文件的存放目录。
35             theProcess = new Process();
36             theProcess.StartInfo = theStartInfo;
37             theProcess.Start();
38             theProcess.WaitForExit();
39             theProcess.Close();
40             return true;
41         }
42         catch (Exception ex)
43         {
44             return false;
45         }
46     }
47  
48     ///
49     /// 解压缩到指定文件夹
50     ///
51     /// 压缩文件存在的目录
52     /// 压缩文件名称
53     /// 解压到文件夹
54     ///
55     protected bool UnRAR(string RARFilePath,string RARFileName,string UnRARFilePath)
56     {
57         //解压缩
58         String therar;
59         RegistryKey theReg;
60         Object theObj;
61         String theInfo;
62         ProcessStartInfo theStartInfo;
63         Process theProcess;
64         try
65          {
66             theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
67             theObj = theReg.GetValue("");
68             therar = theObj.ToString();
69             theReg.Close();
70             therar = therar.Substring(1, therar.Length - 7);
71             theInfo = @" X " + " " + RARFilePath + RARFileName + " " + UnRARFilePath;
72             theStartInfo = new ProcessStartInfo();
73             theStartInfo.FileName = therar;
74             theStartInfo.Arguments = theInfo;
75             theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
76             theProcess = new Process();
77             theProcess.StartInfo = theStartInfo;
78             theProcess.Start();
79             return true;
80         }
81         catch (Exception ex)
82          {
83              return false;
84          }
85     }

注:这种方法在在电脑注册表中未找到应有的路径,未实现,仅供参考。

2.生成zip

通过调用类库ICSharpCode.SharpZipLib.dll

该类库可以从网上下载。也可以从本链接下载:SharpZipLib_0860_Bin.zip

增加两个类:Zip.cs和UnZip.cs

(1)Zip.cs

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 
  6 using System.IO;
  7 using System.Collections;
  8 using ICSharpCode.SharpZipLib.Checksums;
  9 using ICSharpCode.SharpZipLib.Zip;
 10 
 11 
 12 namespace UpLoad
 13 {
 14     /// <summary>
 15     /// 功能:压缩文件
 16     /// creator chaodongwang 2009-11-11
 17     /// </summary>
 18     public class Zip
 19     {
 20         /// <summary>
 21         /// 压缩单个文件
 22         /// </summary>
 23         /// <param name="FileToZip">被压缩的文件名称(包含文件路径)</param>
 24         /// <param name="ZipedFile">压缩后的文件名称(包含文件路径)</param>
 25         /// <param name="CompressionLevel">压缩率0(无压缩)-9(压缩率最高)</param>
 26         /// <param name="BlockSize">缓存大小</param>
 27         public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)
 28         {
 29             //如果文件没有找到,则报错 
 30             if (!System.IO.File.Exists(FileToZip))
 31             {
 32                 throw new System.IO.FileNotFoundException("文件:" + FileToZip + "没有找到!");
 33             }
 34 
 35             if (ZipedFile == string.Empty)
 36             {
 37                 ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";
 38             }
 39 
 40             if (Path.GetExtension(ZipedFile) != ".zip")
 41             {
 42                 ZipedFile = ZipedFile + ".zip";
 43             }
 44 
 45             ////如果指定位置目录不存在,创建该目录
 46             //string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("\\"));
 47             //if (!Directory.Exists(zipedDir))
 48             //    Directory.CreateDirectory(zipedDir);
 49 
 50             //被压缩文件名称
 51             string filename = FileToZip.Substring(FileToZip.LastIndexOf('\\') + 1);
 52             
 53             System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
 54             System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
 55             ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
 56             ZipEntry ZipEntry = new ZipEntry(filename);
 57             ZipStream.PutNextEntry(ZipEntry);
 58             ZipStream.SetLevel(CompressionLevel);
 59             byte[] buffer = new byte[2048];
 60             System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
 61             ZipStream.Write(buffer, 0, size);
 62             try
 63             {
 64                 while (size < StreamToZip.Length)
 65                 {
 66                     int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
 67                     ZipStream.Write(buffer, 0, sizeRead);
 68                     size += sizeRead;
 69                 }
 70             }
 71             catch (System.Exception ex)
 72             {
 73                 throw ex;
 74             }
 75             finally
 76             {
 77                 ZipStream.Finish();
 78                 ZipStream.Close();
 79                 StreamToZip.Close();
 80             }
 81         }
 82 
 83         /// <summary>
 84         /// 压缩文件夹的方法
 85         /// </summary>
 86         public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)
 87         {
 88             //压缩文件为空时默认与压缩文件夹同一级目录
 89             if (ZipedFile == string.Empty)
 90             {
 91                 ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("\\") + 1);
 92                 ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("\\")) +"\\"+ ZipedFile+".zip";
 93             }
 94 
 95             if (Path.GetExtension(ZipedFile) != ".zip")
 96             {
 97                 ZipedFile = ZipedFile + ".zip";
 98             }
 99 
100             using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))
101             {
102                 zipoutputstream.SetLevel(CompressionLevel);
103                 Crc32 crc = new Crc32();
104                 Hashtable fileList = getAllFies(DirToZip);
105                 foreach (DictionaryEntry item in fileList)
106                 {
107                     FileStream fs = File.OpenRead(item.Key.ToString());
108                     byte[] buffer = new byte[fs.Length];
109                     fs.Read(buffer, 0, buffer.Length);
110                     ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length + 1));
111                     entry.DateTime = (DateTime)item.Value;
112                     entry.Size = fs.Length;
113                     fs.Close();
114                     crc.Reset();
115                     crc.Update(buffer);
116                     entry.Crc = crc.Value;
117                     zipoutputstream.PutNextEntry(entry);
118                     zipoutputstream.Write(buffer, 0, buffer.Length);
119                 }
120             }
121         }
122 
123         /// <summary>
124         /// 获取所有文件
125         /// </summary>
126         /// <returns></returns>
127         private Hashtable getAllFies(string dir)
128         {
129             Hashtable FilesList = new Hashtable();
130             DirectoryInfo fileDire = new DirectoryInfo(dir);
131             if (!fileDire.Exists)
132             {
133                 throw new System.IO.FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
134             }
135 
136             this.getAllDirFiles(fileDire, FilesList);
137             this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
138             return FilesList;
139         }
140         /// <summary>
141         /// 获取一个文件夹下的所有文件夹里的文件
142         /// </summary>
143         /// <param name="dirs"></param>
144         /// <param name="filesList"></param>
145         private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
146         {
147             foreach (DirectoryInfo dir in dirs)
148             {
149                 foreach (FileInfo file in dir.GetFiles("*.*"))
150                 {
151                     filesList.Add(file.FullName, file.LastWriteTime);
152                 }
153                 this.getAllDirsFiles(dir.GetDirectories(), filesList);
154             }
155         }
156         /// <summary>
157         /// 获取一个文件夹下的文件
158         /// </summary>
159         /// <param name="strDirName">目录名称</param>
160         /// <param name="filesList">文件列表HastTable</param>
161         private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
162         {
163             foreach (FileInfo file in dir.GetFiles("*.*"))
164             {
165                 filesList.Add(file.FullName, file.LastWriteTime);
166             }
167         }
168     }
169 }


(2)UnZip.cs

 1 using System.Collections.Generic;
 2 using System.Linq;
 3 using System.Web;
 4 
 5 /// <summary> 
 6 /// 解压文件 
 7 /// </summary> 
 8 
 9 using System;
10 using System.Text;
11 using System.Collections;
12 using System.IO;
13 using System.Diagnostics;
14 using System.Runtime.Serialization.Formatters.Binary;
15 using System.Data;
16 
17 using ICSharpCode.SharpZipLib.Zip;
18 using ICSharpCode.SharpZipLib.Zip.Compression;
19 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
20 
21 namespace UpLoad
22 {
23     /// <summary>
24     /// 功能:解压文件
25     /// creator chaodongwang 2009-11-11
26     /// </summary>
27     public class UnZipClass
28     {
29         /// <summary>
30         /// 功能:解压zip格式的文件。
31         /// </summary>
32         /// <param name="zipFilePath">压缩文件路径</param>
33         /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
34         /// <param name="err">出错信息</param>
35         /// <returns>解压是否成功</returns>
36         public void UnZip(string zipFilePath, string unZipDir)
37         {
38             if (zipFilePath == string.Empty)
39             {
40                 throw new Exception("压缩文件不能为空!");
41             }
42             if (!File.Exists(zipFilePath))
43             {
44                 throw new System.IO.FileNotFoundException("压缩文件不存在!");
45             }
46             //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
47             if (unZipDir == string.Empty)
48                 unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
49             if (!unZipDir.EndsWith("\\"))
50                 unZipDir += "\\";
51             if (!Directory.Exists(unZipDir))
52                 Directory.CreateDirectory(unZipDir);
53 
54             using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
55             {
56 
57                 ZipEntry theEntry;
58                 while ((theEntry = s.GetNextEntry()) != null)
59                 {
60                     string directoryName = Path.GetDirectoryName(theEntry.Name);
61                     string fileName = Path.GetFileName(theEntry.Name);
62                     if (directoryName.Length > 0)
63                     {
64                         Directory.CreateDirectory(unZipDir + directoryName);
65                     }
66                     if (!directoryName.EndsWith("\\"))
67                         directoryName += "\\";
68                     if (fileName != String.Empty)
69                     {
70                         using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
71                         {
72 
73                             int size = 2048;
74                             byte[] data = new byte[2048];
75                             while (true)
76                             {
77                                 size = s.Read(data, 0, data.Length);
78                                 if (size > 0)
79                                 {
80                                     streamWriter.Write(data, 0, size);
81                                 }
82                                 else
83                                 {
84                                     break;
85                                 }
86                             }
87                         }
88                     }
89                 }
90             }
91         }
92     } 
93 }

以上这两个类库可以直接在程序里新建类库,然后复制粘贴,直接调用即可。

主程序代码如下所示:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Drawing;
 8 
 9 using Microsoft.Win32;
10 using System.Diagnostics;
11 
12 
13 namespace UpLoad
14 {
15     public partial class UpLoadForm : System.Web.UI.Page
16     {
17         protected void Page_Load(object sender, EventArgs e)
18         {
19 
20         }
21 
22         protected void Button1_Click(object sender, EventArgs e)
23         {
24             if (TextBox1.Text == "") //如果输入为空,则弹出提示
25             {
26                 this.Response.Write("<script>alert('输入为空,请重新输入!');window.opener.location.href=window.opener.location.href;</script>");
27             }
28             else
29             {
30                 //压缩文件夹
31                 string zipPath = TextBox1.Text.Trim(); //获取将要压缩的路径(包括文件夹)
32                 string zipedPath = @"c:\temp"; //压缩文件夹的路径(包括文件夹)
33                 Zip Zc = new Zip();
34                 Zc.ZipDir(zipPath, zipedPath, 6);
35                 this.Response.Write("<script>alert('压缩成功!');window.opener.location.href=window.opener.location.href;</script>");
36 
37                 //解压文件夹
38                 UnZipClass unZip = new UnZipClass();
39                 unZip.UnZip(zipedPath+ ".zip", @"c:\temp"); //要解压文件夹的路径(包括文件名)和解压路径(temp文件夹下的文件就是输入路径文件夹下的文件)
40                 this.Response.Write("<script>alert('解压成功!');window.opener.location.href=window.opener.location.href;</script>");
41 
42             }
43         }
44     }
45 }


本方法经过测试,均已实现。

另外,附上网上下载的参考实例包括源代码,该实例在WinForm下实现:ProgressBar.rar

posted @ 2013-04-14 21:46  zhzhx0318  阅读(2558)  评论(0编辑  收藏  举报