首页 > 其他 > 详细

C# 文件解压

时间:2014-02-15 05:18:23      阅读:455      评论:0      收藏:0      [点我收藏+]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
ZipEnty zp = new ZipEnty();//ZipEnty类 随后贴出
zp.UnZip(realFileName, "E:\\WebAndroid\\Android\\", null);
//待解压目录,解压后目录,密码
 
//ZipEnty
#region
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ICSharpCode.SharpZipLib.Zip;
using System.IO.Compression;
using System.IO;
using Microsoft.Win32;
 
using System.Diagnostics;
using System.Text;
 
namespace RedPlatform.Models.Zip
{
    /// <summary>
    /// WebForm1 的摘要说明。
    /// </summary>
    public class ZipEnty
    {
        public string ServerDir = "E:\\WebAndroid\\Android\\";
        //private void Page_Load(object sender, System.EventArgs e)
        //{
        //    // 在此处放置用户代码以初始化页面
           
        //    //this.ZipFile("01.txt*02.txt*000.zip");  //只是示例,具体的大家自己去实现
        //    //this.ZipFile("01.txt*02.txt*001.zip");
        //    this.UnZipFile("vid20140121150506.zip");
        //}
 
 
        public string ShortDir(string s)
        {
            ServerDir = "E:\\GT视频\\GT视频管理系统部署\\Android\\";
            //将文件的绝对路径转为相对路径
            string d = s.Replace(ServerDir, "");
            return d;
        }
 
 
 
        //压缩文件 p 为客户端传回来的文件列表:文件名+压缩包的名称
        public void ZipFile(string p)
        {
            string[] tmp = p.Split(new char[] { ‘*‘ });  //分离文件列表
            if (tmp[tmp.Length - 1] != ""//压缩包名称不为空
            {
                ZipOutputStream u = new ZipOutputStream(File.Create(ServerDir + tmp[tmp.Length - 1]));            //新建压缩文件流 “ZipOutputStream”
                for (int i = 0; i < tmp.Length - 1; i++)
                {
                    if (tmp[i] != ""//分离出来的文件名不为空
                    {
                        this.AddZipEntry(tmp[i], u, out u); //向压缩文件流加入内容
                    }
                }
                u.Finish(); // 结束压缩
                u.Close();
            }
        }
 
        //添加压缩项目:p 为需压缩的文件或文件夹; u 为现有的源ZipOutputStream;  out j为已添加“ZipEntry”的“ZipOutputStream”
        public void AddZipEntry(string p, ZipOutputStream u, out ZipOutputStream j)
        {
            string s = ServerDir + p;
 
            if (Directory.Exists(s)) //文件夹的处理
            {
                DirectoryInfo di = new DirectoryInfo(s);
 
                //***********以下内容是修订后添加的***********
 
                if (di.GetDirectories().Length <= 0)   //没有子目录
                {
                    ZipEntry z = new ZipEntry(p + ""); //末尾“""”用于文件夹的标记
                    u.PutNextEntry(z);
                }
 
                //***************以上内容是修订后添加的***************
 
 
                foreach (DirectoryInfo tem in di.GetDirectories()) //获取子目录
                {
                    ZipEntry z = new ZipEntry(this.ShortDir(tem.FullName) + ""); //末尾“""”用于文件夹的标记
                    u.PutNextEntry(z);    //此句不可少,否则空目录不会被添加
                    s = this.ShortDir(tem.FullName);
                    this.AddZipEntry(s, u, out u);       //递归
                }
                foreach (FileInfo temp in di.GetFiles())  //获取此目录的文件
                {
                    s = this.ShortDir(temp.FullName);
                    this.AddZipEntry(s, u, out u);       //递归
                }
            }
            else if (File.Exists(s)) //文件的处理
            {
                u.SetLevel(9);      //压缩等级
                FileStream f = File.OpenRead(s);
                byte[] b = new byte[f.Length];
                f.Read(b, 0, b.Length);           //将文件流加入缓冲字节中
                ZipEntry z = new ZipEntry(this.ShortDir(s));
                u.PutNextEntry(z);              //为压缩文件流提供一个容器
                u.Write(b, 0, b.Length); //写入字节
                f.Close();
            }
            j = u;    //返回已添加数据的“ZipOutputStream”
        }
 
 
        public void UnZipFile(string p)   //解压缩
        {
 
            string un_time = System.DateTime.Now.ToString("yyyyMMddhhmmss");
            string un_dir = ServerDir + "Unzip-" + un_time;
            Directory.CreateDirectory(un_dir);     //创建以解压时间为名称的文件夹
            ZipInputStream f = new ZipInputStream(File.OpenRead(ServerDir + p)); //读取压缩文件,并用此文件流新建 “ZipInputStream”对象
            //ICSharpCode.SharpZipLib.Zip.ZipFile f1 = new ICSharpCode.SharpZipLib.Zip.ZipFile(ServerDir + p);
             
            A: ZipEntry zp = f.GetNextEntry();    //获取解压文件流中的项目。 另注(我的理解):在压缩包里每个文件都以“ZipEntry”形式存在,其中包括存放文件的目录信息。如果空目录被压缩,该目录下将出现一个名称为空、大小为 0 、“Crc”属性为 00000000 的“文件”。此文件只是个标记,不会被解压。
 
            while (zp != null)
            {
                string un_tmp2;
                if (zp.Name.IndexOf("") >= 0) //获取文件的目录信息
                {
                    int tmp1 = zp.Name.LastIndexOf("");
                    un_tmp2 = zp.Name.Substring(0, tmp1);
                    Directory.CreateDirectory(un_dir + "" + un_tmp2 + ""); //必须先创建目录,否则解压失败 --- (A) 关系到下面的步骤(B)
                }
                if (!zp.IsDirectory && zp.Crc != 00000000L) //此“ZipEntry”不是“标记文件”
                {
                    int i = 2048;
                    byte[] b = new byte[i];  //每次缓冲 2048 字节
                    FileStream s = File.Create(un_dir + "" + zp.Name); //(B)-新建文件流
                    while (true) //持续读取字节,直到一个“ZipEntry”字节读完
                    {
                        i = f.Read(b, 0, b.Length); //读取“ZipEntry”中的字节
                        if (i > 0)
                        {
                            s.Write(b, 0, i); //将字节写入新建的文件流
                        }
                        else
                        {
                            break; //读取的字节为 0 ,跳出循环
                        }
                    }
                    s.Close();
                }
                goto A; //进入下一个“ZipEntry”
            }
            f.Close();
        }
 
        #region 解压文件
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">指定解压目标目录</param>
        /// <param name="Password"></param>
        public static void WritetoLog(string txt)
        {
 
            string path = "D:\\mylog\\log.txt";
            //path  += DateTime.Now.ToString("yyyyMMdd-hhmmss") + ".txt";
 
            FileStream fs;
 
            StreamWriter sw;
 
            fs = new FileStream(path, FileMode.Append);
 
            sw = new StreamWriter(fs, Encoding.Default);
 
            sw.Write(txt);
            sw.Close();
            fs.Close();
 
 
 
        }
        public void UnZip(string FileToUpZip, string ZipedFolder, string Password)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
 
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }
 
            ZipInputStream s = null;
            ZipEntry theEntry = null;
 
            string fileName;
            FileStream streamWriter = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                s.Password = Password;
                theEntry = s.GetNextEntry();
                //while ((theEntry = s.GetNextEntry()) != null)
                //{  
                if (theEntry.Name != String.Empty)
                {
                    fileName = Path.Combine(ZipedFolder, theEntry.Name);
                    /**/
                    ///判断文件路径是否是文件夹
                    if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                    {
                        Directory.CreateDirectory(fileName);
                        //continue;
                    }
 
                    streamWriter = File.Create(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
                        {
                            break;
                        }
                    }
 
                    //File.Delete(FileToUpZip);
                }
                //}
            }
            catch (Exception ex)
            {
                WritetoLog(ex.ToString());
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
        #endregion
 
 
 
        /// <summary>
        /// //解压  必须装有WinRar
        /// </summary>
        /// <param name="rarfilepath"></param> //压缩文件路劲
        /// <param name="filepath"></param>   //解压保存路径
        public  string uncompress(string rarfilepath, string filepath)
        {
            try
            {
                string rar;
                RegistryKey reg;
                string args;
                ProcessStartInfo startInfo;
                Process process;
                reg = Registry.ClassesRoot.OpenSubKey(@"Applications/WinRar.exe/Shell/Open/Command");//WinRar位置
                rar = reg.GetValue("").ToString();
                reg.Close();
                rar = rar.Substring(1, rar.Length - 7);
                args = " X " + rarfilepath + " " + filepath;
                startInfo = new ProcessStartInfo();
                startInfo.FileName = rar;
                startInfo.Arguments = args;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process = new Process();
                process.StartInfo = startInfo;
                process.Start();
                return "success";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
 
 
        
 
 
 
 
         
    }
}
#endregion

  

C# 文件解压

原文:http://www.cnblogs.com/cowkeys/p/3549820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!