二進制轉文件以及文件壓縮和解壓縮


 1         #region 將本地壓縮文件轉換為Base64編碼
 2         /// <summary>
 3         /// 將本地壓縮文件轉換為Base64編碼
 4         /// </summary>
 5         /// <returns></returns>
 6         public string ReturnBase64Code()
 7         {
 8             //從服務器獲取到的文件路徑
 9             string ys_filePath =  rootDirectoryPath + @"\hx.zip";   
10             //將壓縮文件轉換為二進制
11             using (FileStream fs = new FileStream(ys_filePath, FileMode.Open))
12             {
13                 byte[] bytes = new byte[fs.Length];
14                 int count = Convert.ToInt32(fs.Length);
15                 fs.Read(bytes, 0, count);
16                 fs.Close();
17                 //將二進制轉為為base64
18                 return Convert.ToBase64String(bytes);
19             } 
20         }
21         #endregion
 1         #region 直接刪除指定目錄下的所有文件及文件夾(保留目錄)
 2         /// <summary>
 3         /// 直接刪除指定目錄下的所有文件及文件夾(保留目錄)
 4         /// </summary>
 5         /// <param name="strPath">文件夾路徑</param>
 6         /// <returns>執行結果</returns>
 7         public bool DeleteDir(string strPath)     
 8  9             try         
10             {
11                 strPath = @strPath.Trim().ToString();// 清除空格 
12                 if (System.IO.Directory.Exists(strPath))  // 判斷文件夾是否存在            
13 14                     // 獲得文件夾數組 
15                     string[] strDirs = System.IO.Directory.GetDirectories(strPath); // 獲得文件數組 
16                     string[] strFiles = System.IO.Directory.GetFiles(strPath); // 遍歷所有子文件夾 
17                     foreach (string strFile in strFiles)                 
18 19                         // 刪除文件夾 
20                         System.IO.File.Delete(strFile);                 
21 22                     // 遍歷所有文件 
23                     foreach (string strdir in strDirs)                 
24 25                         // 刪除文件 
26                         System.IO.Directory.Delete(strdir, true);                 
27                     }             
28                 }
29                 return true;                     
30 31             catch (Exception Exp) // 異常處理         
32             {
33                 System.Diagnostics.Debug.Write(Exp.Message.ToString()); // 異常信息 
34                 return false;         
35             }  
36         }
37         #endregion
 
         
 1         #region 定時下載廣告文件
 2         public void theout(object source, System.Timers.ElapsedEventArgs e)
 3         {
 4             string str = ReturnBase64Code();//將二進制轉為為base64
 5 
 6             byte[] outputb = Convert.FromBase64String(str);//將base64編碼轉換為二進制
 7 
 8             //將二進制轉換為壓縮文件
 9             string path = rootDirectoryPath + @"\new_hx.zip";//壓縮文件的地址 
10             File.WriteAllBytes(path, outputb);
11 
12             //刪除廣告目錄下已經存在的文件
13             if (Directory.Exists(filePath))
14             {
15                 DeleteDir(filePath);
16             }
17             //解壓文件
18             bool result = bonkerZip.UnZipFile(path, filePath); //  DeCompressionZip
19             if (!result)
20             {
21                 ErrorLog.WriteErrorLog(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "廣告文件解壓失敗,失敗原因:"+bonkerZip.errorMsg);
22             }
23             webBrowser1.Navigate(filePath+@"\index.html");
24         } 
25         #endregion
  1 public class BonkerZip
  2     {
  3         /// <summary>
  4         /// 存放待壓縮的文件的絕對路徑
  5         /// </summary>
  6         private List<string> AbsolutePaths { set; get; }
  7         public string errorMsg { set; get; }
  8 
  9         public BonkerZip()
 10         {
 11             errorMsg = "";
 12             AbsolutePaths = new List<string>();
 13         }
 14         /// <summary>
 15         /// 添加壓縮文件
 16         /// </summary>
 17         /// <param name="_fileAbsolutePath">文件的絕對路徑</param>
 18         public void AddFile(string _fileAbsolutePath)
 19         {
 20             AbsolutePaths.Add(_fileAbsolutePath);
 21         }
 22         /// <summary>
 23         /// 壓縮文件或者文件夾
 24         /// </summary>
 25         /// <param name="_depositPath">壓縮后文件的存放路徑   如C:\\windows\abc.zip</param>
 26         /// <returns></returns>
 27         public bool CompressionZip(string _depositPath)
 28         {
 29             bool result = true;
 30             FileStream fs = null;
 31             try
 32             {
 33                 ZipOutputStream ComStream = new ZipOutputStream(File.Create(_depositPath));
 34                 ComStream.SetLevel(9);      //壓縮等級
 35                 foreach (string path in AbsolutePaths)
 36                 {
 37                     //如果是目錄
 38                     if (Directory.Exists(path))
 39                     {
 40                         ZipFloder(path, ComStream, path);
 41                     }
 42                     else if (File.Exists(path))//如果是文件
 43                     {
 44                          fs = File.OpenRead(path);
 45                         byte[] bts = new byte[fs.Length];
 46                         fs.Read(bts, 0, bts.Length);
 47                         ZipEntry ze = new ZipEntry(new FileInfo(path).Name);
 48                         ComStream.PutNextEntry(ze);             //為壓縮文件流提供一個容器
 49                         ComStream.Write(bts, 0, bts.Length);  //寫入字節
 50                     }
 51                 }
 52                 ComStream.Finish(); // 結束壓縮
 53                 ComStream.Close();
 54             }
 55             catch (Exception ex)
 56             {
 57                 if (fs != null)
 58                 {
 59                     fs.Close();
 60                 }
 61                 errorMsg = ex.Message;
 62                 result = false;
 63             }
 64             return result;
 65         }
 66         //壓縮文件夾
 67         private void ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath)
 68         {
 69             foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos())
 70             {
 71                 if (Directory.Exists(item.FullName))
 72                 {
 73                     ZipFloder(_OfloderPath, zos, item.FullName);
 74                 }
 75                 else if (File.Exists(item.FullName))//如果是文件
 76                 {
 77                     DirectoryInfo ODir = new DirectoryInfo(_OfloderPath);
 78                     string fullName2 = new FileInfo(item.FullName).FullName;
 79                     string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);//獲取相對目錄
 80                     FileStream fs = File.OpenRead(fullName2);
 81                     byte[] bts = new byte[fs.Length];
 82                     fs.Read(bts, 0, bts.Length);
 83                     ZipEntry ze = new ZipEntry(path);
 84                     zos.PutNextEntry(ze);             //為壓縮文件流提供一個容器
 85                     zos.Write(bts, 0, bts.Length);  //寫入字節
 86                 }
 87             }
 88         }
 89         /// <summary>
 90         /// 解壓
 91         /// </summary>
 92         /// <param name="_depositPath">壓縮文件路徑</param>
 93         /// <param name="_floderPath">解壓的路徑</param>
 94         /// <returns></returns>
 95         public bool DeCompressionZip(string _depositPath, string _floderPath)
 96         {
 97             bool result = true;
 98             FileStream fs=null;
 99             try
100             {
101                 using (ZipInputStream InpStream = new ZipInputStream(File.OpenRead(_depositPath)))
102                 {
103                     ZipEntry ze = InpStream.GetNextEntry();//獲取壓縮文件中的每一個文件
104                     Directory.CreateDirectory(_floderPath);//創建解壓文件夾
105                     while (ze != null)//如果解壓完ze則是null
106                     {
107                         if (ze.IsFile)//壓縮zipINputStream里面存的都是文件。帶文件夾的文件名字是文件夾\\文件名
108                         {
109                             string[] strs = ze.Name.Split('\\');//如果文件名中包含’\\‘則表明有文件夾
110                             if (strs.Length > 1)
111                             {
112                                 //兩層循環用於一層一層創建文件夾
113                                 for (int i = 0; i < strs.Length - 1; i++)
114                                 {
115                                     string floderPath = _floderPath;
116                                     for (int j = 0; j < i; j++)
117                                     {
118                                         floderPath = floderPath + "\\" + strs[j];
119                                     }
120                                     floderPath = floderPath + "\\" + strs[i];
121                                     Directory.CreateDirectory(floderPath);
122                                 }
123                             }
124                             fs = new FileStream(_floderPath + "\\" + ze.Name, FileMode.OpenOrCreate, FileAccess.Write);//創建文件
125                             //循環讀取文件到文件流中
126                             while (true)
127                             {
128                                 byte[] bts = new byte[1024];
129                                 int i = InpStream.Read(bts, 0, bts.Length);
130                                 if (i > 0)
131                                 {
132                                     fs.Write(bts, 0, i);
133                                 }
134                                 else
135                                 {
136                                     fs.Flush();
137                                     fs.Close();
138                                     break;
139                                 }
140                             }
141                         }
142                         ze = InpStream.GetNextEntry();
143                     }
144                 }
145             }
146             catch (Exception ex)
147             {
148                 if (fs != null)
149                 {
150                     fs.Close();
151                 }
152                 errorMsg = ex.Message;
153                 result = false;
154             }
155             finally
156             {
157                 if (fs != null)
158                 {
159                     fs.Close();
160                     fs.Dispose();
161                 }
162             }
163             return result;
164         }
165 
166 
167         /// <summary>
168         /// 功能:解壓zip格式的文件。
169         /// </summary>
170         /// <param name="zipFilePath">壓縮文件路徑</param>
171         /// <param name="unZipDir">解壓文件存放路徑,為空時默認與壓縮文件同一級目錄下,跟壓縮文件同名的文件夾</param>
172         /// <param name="err">出錯信息</param>
173         /// <returns>解壓是否成功</returns>
174         public bool UnZipFile(string zipFilePath, string unZipDir)// , out string err
175         {
176             // err = "";
177             if (zipFilePath == string.Empty)
178             {
179                 //err = "壓縮文件不能為空!";
180                 return false;
181             }
182             if (!File.Exists(zipFilePath))
183             {
184                 //err = "壓縮文件不存在!";
185                 return false;
186             }
187             //解壓文件夾為空時默認與壓縮文件同一級目錄下,跟壓縮文件同名的文件夾
188             if (unZipDir == string.Empty)
189                 unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
190             if (!unZipDir.EndsWith("\\"))
191                 unZipDir += "\\";
192             if (!Directory.Exists(unZipDir))
193                 Directory.CreateDirectory(unZipDir);
194 
195             try
196             {
197                 using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath.ToLower())))
198                 {
199 
200                     ZipEntry theEntry;
201                     while ((theEntry = s.GetNextEntry()) != null)
202                     {
203                         string directoryName = Path.GetDirectoryName(theEntry.Name);
204                         string fileName = Path.GetFileName(theEntry.Name);
205                         if (directoryName.Length > 0)
206                         {
207                             Directory.CreateDirectory(unZipDir + directoryName);
208                         }
209                         if (!directoryName.EndsWith("\\"))
210                             directoryName += "\\";
211                         if (fileName != String.Empty)
212                         {
213                             using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
214                             {
215 
216                                 int size = 2048;
217                                 byte[] data = new byte[2048];
218                                 while (true)
219                                 {
220                                     size = s.Read(data, 0, data.Length);
221                                     if (size > 0)
222                                     {
223                                         streamWriter.Write(data, 0, size);
224                                     }
225                                     else
226                                     {
227                                         break;
228                                     }
229                                 }
230                             }
231                         }
232                     }//while
233                 }
234             }
235             catch (Exception ex)
236             {
237                 //err = ex.Message;
238                 return false;
239             }
240             return true;
241         }//解壓結束
242 
243     }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM