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

ICSharpCode.SharpZipLib.dll下載地址

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

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
#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文件夾中,並清除原來未壓縮日誌。

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
#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";
                    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、壓縮文件

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
#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、解壓縮
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
#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;
     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、壓縮文件夾

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
#region 壓縮文件夾
/// <SUMMARY>    
/// 壓縮文件夾    
/// </SUMMARY>    
/// <PARAM name="dirPath">要打包的文件夾</PARAM>    
/// <PARAM name="GzipFileName">目標文件名</PARAM>    
/// <PARAM name="CompressionLevel">壓縮品質級別(0~9)</PARAM>    
/// <PARAM name="deleteDir">是否刪除原文件夾</PARAM>  
public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
{
    //壓縮文件爲空時默認與壓縮文件夾同一級目錄    
    if (GzipFileName == string.Empty)
    {
        GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
        GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
    }
    //if (Path.GetExtension(GzipFileName) != ".zip")  
    //{  
    //    GzipFileName = GzipFileName + ".zip";  
    //}  
    using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
    {
        zipoutputstream.SetLevel(CompressionLevel);
        ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
        Dictionary<STRING, DateTime> fileList = GetAllFies(dirPath);
        foreach (KeyValuePair<STRING, DateTime> item in fileList)
        {
            FileStream fs = File.OpenRead(item.Key.ToString());
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
            entry.DateTime = item.Value;
            entry.Size = fs.Length;
            fs.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            zipoutputstream.PutNextEntry(entry);
            zipoutputstream.Write(buffer, 0, buffer.Length);
        }
    }
    if (deleteDir)
    {
        Directory.Delete(dirPath, true);
    }
}
#endregion
6、獲取傳遞目錄參數Dir下所有文件(EG:GetAllFies(@"F:\WorkSpace")獲取F盤WorkSpace目錄下所有文件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#region 獲取所有文件
/// <SUMMARY>    
/// 獲取所有文件    
/// </SUMMARY>    
/// <RETURNS></RETURNS>    
private static Dictionary<STRING, DateTime> GetAllFies(string dir)
{
    Dictionary<STRING, DateTime> FilesList = new Dictionary<STRING, DateTime>();
    DirectoryInfo fileDire = new DirectoryInfo(dir);
    if (!fileDire.Exists)
    {
        throw new System.IO.FileNotFoundException("目錄:" + fileDire.FullName + "沒有找到!");
    }
    GetAllDirFiles(fileDire, FilesList);
    GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
    return FilesList;
}
#endregion
7、獲取一個文件夾下的所有文件夾裏的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#region 獲取一個文件夾下的所有文件夾裏的文件
/// <SUMMARY>    
/// 獲取一個文件夾下的所有文件夾裏的文件    
/// </SUMMARY>    
/// <PARAM name="dirs"></PARAM>    
/// <PARAM name="filesList"></PARAM>    
private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<STRING, DateTime> filesList)  
{  
    foreach (DirectoryInfo dir in dirs)  
    {  
        foreach (FileInfo file in dir.GetFiles("*.*"))  
        {  
            filesList.Add(file.FullName, file.LastWriteTime);  
        }  
        GetAllDirsFiles(dir.GetDirectories(), filesList);  
    }  
}  
#endregion
8、獲取一個文件夾下的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#region 獲取一個文件夾下的文件
/// <SUMMARY>    
/// 獲取一個文件夾下的文件    
/// </SUMMARY>    
/// <PARAM name="dir">目錄名稱</PARAM>    
/// <PARAM name="filesList">文件列表HastTable</PARAM>    
private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<STRING, DateTime> filesList)  
{  
    foreach (FileInfo file in dir.GetFiles("*.*"))  
    {  
        filesList.Add(file.FullName, file.LastWriteTime);  
    }  
}  
#endregion


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章