程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#下利用ICSharpCode.SharpZipLib.dll實現文件/文件夾壓縮和解壓縮

C#下利用ICSharpCode.SharpZipLib.dll實現文件/文件夾壓縮和解壓縮

編輯:關於C#

1、壓縮某個指定目錄下日志,將日志壓縮到CompressionDirectory文件夾中,並清除原來未壓縮日志。

#region 壓縮logs目錄下日志  
 public static void CompresslogDic()  
 {       
     try
     {  
         string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "logs";  
         DirectoryInfo logsDic = new DirectoryInfo(logFilePath);  
         FileInfo[] bipLog = logsDic.GetFiles();  
         DateTime dt = DateTime.Now;  
         List<FileInfo> logsInOneDay = new List<FileInfo>();  
         for (int i = 0; i < bipLog.Length; i++)  
         {  
             if (bipLog[i].Name.Substring(bipLog[i].Name.Length - 3) != "zip")  
             {  
                 logsInOneDay.Add(bipLog[i]);  
             }  
         }  
         if (logsInOneDay.Count > 0)  
         {  
             try
             {  
                 if (!Directory.Exists(logsDic.FullName + "\\CompressionDirectory"))  
                 {  
                     Directory.CreateDirectory(logsDic.FullName + "\\CompressionDirectory");  
                 }  
                 string compressFileName = dt.ToString("yyyy-MM-dd");  
                 if (File.Exists(logsDic.FullName + "\\CompressionDirectory\\" + dt.ToString("yyyy-MM-dd") + ".zip"))  
                 {  
                     Guid guid = Guid.NewGuid();  
                     compressFileName = compressFileName + "-" + guid.ToString();  
                 }  
                 compressFileName += ".zip";  
                 Compress(logsInOneDay, logsDic.FullName + "\\CompressionDirectory\\" + compressFileName, 9, 100);  
                 foreach (FileInfo fileInfo in logsInOneDay)  
                 {  
                     try
                     {  
                         fileInfo.Delete();  
                     }  
                     catch (Exception e)  
                     {  
                         //錯誤信息記錄處理  
                     }  
                 }  
             }  
             catch (Exception e)  
             {  
                 //錯誤信息記錄處理  
             }  
         }           
     }  
     catch (Exception e)  
     {  
         //錯誤信息記錄處理  
     }          
 }  
 #endregion

2、壓縮指定目錄子目錄下日志,將日志壓縮到CompressionDirectory文件夾中,並清除原來未壓縮日志。

#region 壓縮logs子目錄下日志  
public static void CompresslogsDic()  
{  
    try
    {  
        string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "logs";                 
        DirectoryInfo logsDic = new DirectoryInfo(logFilePath);  
        FileInfo[] bipLog = logsDic.GetFiles();  
        DateTime dt = DateTime.Now;  
        DirectoryInfo[] subLosgDic = logsDic.GetDirectories();  
        foreach (DirectoryInfo bankDic in subLosgDic)  
        {  
            dt = DateTime.Now;  
            bipLog = bankDic.GetFiles();  
            List<FileInfo> logsInOneDay = new List<FileInfo>();  
            for (int i = 0; i < bipLog.Length; i++)  
            {  
                if (bipLog[i].Name.Substring(bipLog[i].Name.Length - 3) != "zip")  
                {  
                    logsInOneDay.Add(bipLog[i]);  
                }  
            }  
            if (logsInOneDay.Count > 0)  
            {  
                try
                {  
                    if (!Directory.Exists(bankDic.FullName + "\\CompressionDirectory"))  
                    {  
                        Directory.CreateDirectory(bankDic.FullName + "\\CompressionDirectory");  
                    }  
                    string compressFileName = dt.ToString("yyyy-MM-dd");  
                    if (File.Exists(bankDic.FullName + "\\CompressionDirectory\\" + dt.ToString("yyyy-MM-dd") + ".zip"))  
                    {  
                        Guid guid = Guid.NewGuid();  
                        compressFileName = compressFileName + "-" + guid.ToString();  
                    }  
                    compressFileName += ".zip";  
				// 本文URL:http://www.bianceng.cn/Programming/csharp/201410/45594.htm
                    Compress(logsInOneDay, bankDic.FullName + "\\CompressionDirectory\\" + compressFileName, 9, 100);  
                    foreach (FileInfo fileInfo in logsInOneDay)  
                    {  
                        try
                        {  
                            fileInfo.Delete();  
                        }  
                        catch (Exception e)  
                        {  
                            //錯誤信息記錄處理  
                        }  
                    }  
                }  
                catch (Exception e)  
                {  
                    //錯誤信息記錄處理  
                }  
            }  
        }               
    }  
    catch (Exception e)  
    {  
        //錯誤信息記錄處理  
    }  
}  
#endregion

3、壓縮文件

#region 壓縮文件  
/// <summary>  
/// 壓縮文件  
/// </summary>  
/// <param name="fileNames">要打包的文件列表</param>  
/// <param name="GzipFileName">目標文件名</param>  
/// <param name="CompressionLevel">壓縮品質級別(0~9)</param>  
/// <param name="SleepTimer">休眠時間(單位毫秒)</param>       
public static void Compress(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, int SleepTimer)  
{  
    ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));  
    try
    {  
        s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression  
        foreach (FileInfo file in fileNames)  
        {  
            FileStream fs = null;  
            try
            {  
                fs = file.Open(FileMode.Open, FileAccess.ReadWrite);  
            }  
            catch
            {  
                continue;  
            }  
            // 將文件分批讀入緩沖區  
            byte[] data = new byte[2048];  
            int size = 2048;  
            ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));  
            entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);  
            s.PutNextEntry(entry);  
            while (true)  
            {  
                size = fs.Read(data, 0, size);  
                if (size <= 0) break;  
                s.Write(data, 0, size);  
            }  
            fs.Close();  
            Thread.Sleep(SleepTimer);  
        }  
    }  
    finally
    {  
        s.Finish();  
        s.Close();  
    }  
}  
#endregion

4、解壓縮

#region 解壓縮文件  
 /// <summary>  
 /// 解壓縮文件  
 /// </summary>  
 /// <param name="GzipFile">壓縮包文件名</param>  
 /// <param name="targetPath">解壓縮目標路徑</param>         
 public static void Decompress(string GzipFile, string targetPath)  
 {  
     //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";  
     string directoryName = targetPath;  
	 // 本文URL:http://www.bianceng.cn/Programming/csharp/201410/45594.htm
     if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解壓目錄  
     string CurrentDirectory = directoryName;  
     byte[] data = new byte[2048];  
     int size = 2048;  
     ZipEntry theEntry = null;  
     using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))  
     {  
         while ((theEntry = s.GetNextEntry()) != null)  
         {  
             if (theEntry.IsDirectory)  
             {// 該結點是目錄  
                 if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);  
             }  
             else
             {  
                 if (theEntry.Name != String.Empty)  
                 {  
                     //檢查多級目錄是否存在    
                     if (theEntry.Name.Contains("//"))  
                     {  
                         string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);  
                         if (!Directory.Exists(parentDirPath))  
                         {  
                             Directory.CreateDirectory(CurrentDirectory + parentDirPath);  
                         }  
                     }    
                     //解壓文件到指定的目錄  
                     using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))  
                     {  
                         while (true)  
                         {  
                             size = s.Read(data, 0, data.Length);  
                             if (size <= 0) break;  
      
                             streamWriter.Write(data, 0, size);  
                         }  
                         streamWriter.Close();  
                     }  
                 }  
             }  
         }  
         s.Close();  
     }  
 }  
 #endregion

5、壓縮文件夾

01.#region 壓縮文件夾   
02./// <summary>
03./// 壓縮文件夾
04./// </summary>
05./// <param name="dirPath">要打包的文件夾</param>
06./// <param name="GzipFileName">目標文件名</param>
07./// <param name="CompressionLevel">壓縮品質級別(0~9)</param>
08./// <param name="deleteDir">是否刪除原文件夾</param>
09.public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
10.{
11. //壓縮文件為空時默認與壓縮文件夾同一級目錄
12. if (GzipFileName == string.Empty)
13. {
14. GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
15. GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
16. }
17. //if (Path.GetExtension(GzipFileName) != ".zip")
18. //{
19. // GzipFileName = GzipFileName + ".zip";
20. //}
21. using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
22. {
23. zipoutputstream.SetLevel(CompressionLevel);
24. ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
25. Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
26. foreach (KeyValuePair<string, DateTime> item in fileList)
27. {
28. FileStream fs = File.OpenRead(item.Key.ToString());
29. byte[] buffer = new byte[fs.Length];
30. fs.Read(buffer, 0, buffer.Length);
31. ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
32. entry.DateTime = item.Value;
33. entry.Size = fs.Length;
34. fs.Close();
35. crc.Reset();
36. crc.Update(buffer);
37. entry.Crc = crc.Value;
38. zipoutputstream.PutNextEntry(entry);
39. zipoutputstream.Write(buffer, 0, buffer.Length);
40. }
41. }
42. if (deleteDir)
43. {
44. Directory.Delete(dirPath, true);
45. }
46.}
47.#endregion

6、獲取傳遞目錄參數Dir下所有文件(EG:GetAllFies(@"F:\WorkSpace")獲取F盤WorkSpace目錄下所有文件)

01.#region 獲取所有文件
02./// <summary>
03./// 獲取所有文件
04./// </summary>
05./// <returns></returns>
06.private static Dictionary<string, DateTime> GetAllFies(string dir)
07.{
08. Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
09. DirectoryInfo fileDire = new DirectoryInfo(dir);
10. if (!fileDire.Exists)
11. {
12. throw new System.IO.FileNotFoundException("目錄:" + fileDire.FullName + "沒有找到!");
13. }
14. GetAllDirFiles(fileDire, FilesList);
15. GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
16. return FilesList;
17.}
18.#endregion

7、獲取一個文件夾下的所有文件夾裡的文件

01.#region 獲取一個文件夾下的所有文件夾裡的文件
02./// <summary>
03./// 獲取一個文件夾下的所有文件夾裡的文件
04./// </summary>
05./// <param name="dirs"></param>
06./// <param name="filesList"></param>
07.private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
08.{
09. foreach (DirectoryInfo dir in dirs)
10. {
11. foreach (FileInfo file in dir.GetFiles("*.*"))
12. {
13. filesList.Add(file.FullName, file.LastWriteTime);
14. }
15. GetAllDirsFiles(dir.GetDirectories(), filesList);
16. }
17.}
18.#endregion

8、獲取一個文件夾下的文件

01.#region 獲取一個文件夾下的文件
02./// <summary>
03./// 獲取一個文件夾下的文件
04./// </summary>
05./// <param name="dir">目錄名稱</param>
06./// <param name="filesList">文件列表HastTable</param>
07.private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
08.{
09. foreach (FileInfo file in dir.GetFiles("*.*"))
10. {
11. filesList.Add(file.FullName, file.LastWriteTime);
12. }
13.}
14.#endregion

ICSharpCode.SharpZipLib.dll下載地址:http://download.csdn.net/detail/xunzaosiyecao/7670099

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved