C# 實現文件壓縮-- 背景:服務器Log.txt 過多,佔用過多硬盤空間,壓縮備份后節省空間資源

1、壓縮實現代碼如下: 調用ICSharpCode.SharpZipLib.dll(free software,可以搜到源碼).

  • 轉移指定目錄文件夾轉移到目標文件夾
  • 壓縮目標文件夾
  • 刪除目標文件夾
using System;
using System.Xml.Linq;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

public class AutoZipFile
{
    private static string _fromPath;
    private static string _toPath;

    public AutoZipFile()
    {
    }

    public static void FileToZip()
    {
        //string _file = ConfigurationManager.AppSettings["ServicePoolPath"] + "\ZipFileConfig.xml";
        string _file = @"D:WMSGroceryipFileConfig.xml";
        XDocument xDoc = XDocument.Load(_file);
        XElement xEle = XElement.Parse(xDoc.ToString());

        foreach (XElement str in xEle.Elements("zipPath"))
        {
            var element = str.Element("fp");
            if (element != null) _fromPath = element.Value;
            element = str.Element("tp");
            if (element != null) _toPath = element.Value;

            //轉移后文件壓縮路徑
            string zipPath = _toPath + DateTime.Now.ToString("yyyyMMddhh24mmss");

            //文件移到目標路徑
            MoveDir(_fromPath, _toPath);

            //目標文件創建壓縮
            CreateZipFile(_toPath, zipPath);

            //若目標文件壓縮生成的文件不為空(即壓縮成功),刪除目標文件
            FileInfo fileInfo = new FileInfo(zipPath);
            if (fileInfo.Length > 100)
            {
                DeleteDir(_toPath);
            }
        }
    }

    /// <summary>
    /// 将整个文件夹复制到目标文件夹中。
    /// </summary>
    /// <param name="srcPath">源文件夹</param>
    /// <param name="aimPath">目标文件夹</param>
    public static void CopyDir(string srcPath, string aimPath)
    {
        try
        {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                aimPath += Path.DirectorySeparatorChar;
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(aimPath))
                Directory.CreateDirectory(aimPath);
            // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
            // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(srcPath);
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                    CopyDir(file, aimPath + Path.GetFileName(file));
                // 否则直接Copy文件
                else
                    File.Copy(file, aimPath + Path.GetFileName(file), true);
            }
        }
        catch
        {
            Console.WriteLine(@"Connot copy file {0} to {1}!", srcPath, aimPath);
        }
    }

    /// <summary>
    /// 将整个文件夹移轉到目标文件夹中。
    /// </summary>
    /// <param name="srcPath">源文件夹</param>
    /// <param name="aimPath">目标文件夹</param>
    public static void MoveDir(string srcPath, string aimPath)
    {
        try
        {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                aimPath += Path.DirectorySeparatorChar;
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(aimPath))
                Directory.CreateDirectory(aimPath);
            // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
            // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(srcPath);
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                //如果是當天創建的不移動(可能還在使用中,防止移動造成錯誤)
                if (Equals(Directory.GetCreationTime(file).ToShortDateString(), DateTime.Now.ToShortDateString()))
                {
                    continue;
                }
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                    MoveDir(file, aimPath + Path.GetFileName(file));
                // 否则直接Copy文件
                else
                    File.Move(file, aimPath + Path.GetFileName(file));
            }
        }
        catch
        {
            Console.WriteLine(@"Connot move file {0} to {1}!", srcPath, aimPath);
        }
    }

    /// <summary>
    /// 将整个文件夹删除。
    /// </summary>
    /// <param name="aimPath">目标文件夹</param>
    public static void DeleteDir(string aimPath)
    {
        try
        {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                aimPath += Path.DirectorySeparatorChar;
            // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
            // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(aimPath);
            string[] fileList = Directory.GetFileSystemEntries(aimPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
                if (Directory.Exists(file))
                {
                    DeleteDir(aimPath + Path.GetFileName(file));
                }
                // 否则直接Delete文件
                else
                {
                    File.Delete(aimPath + Path.GetFileName(file));
                }
            }
            //删除文件夹
            //System.IO .Directory .Delete (aimPath,true);
        }
        catch
        {
            Console.WriteLine(@"Cannot Delete file '{0}'!", aimPath);
        }
    }

    /// <summary>
    /// 指定目錄創建壓縮文件。
    /// </summary>
    /// <param name="filesPath">指定目錄</param>
    /// <param name="zipFilePath">指定壓縮文件目錄</param>
    public static void CreateZipFile(string filesPath, string zipFilePath)
    {

        if (!Directory.Exists(filesPath))
        {
            Console.WriteLine(@"Cannot find directory '{0}'", filesPath);
            return;
        }

        try
        {
            string[] filenames = Directory.GetFiles(filesPath);

            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
            {

                s.SetLevel(9); // 压缩级别 0-9
                //s.Password = "123"; //Zip压缩文件密码
                byte[] buffer = new byte[4096]; //缓冲区大小
                foreach (string file in filenames)
                {
                    ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(file))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }
                s.Finish();
                s.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(@"Exception during processing {0}", ex);
        }
    }

    /// <summary>
    /// 文件解壓縮
    /// </summary>
    /// <param name="zipFilePath"></param>
    public static void UnZipFile(string zipFilePath)
    {
        if (!File.Exists(zipFilePath))
        {
            Console.WriteLine(@"Cannot find file '{0}'", zipFilePath);
            return;
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
        {

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {

                Console.WriteLine(theEntry.Name);

                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName = Path.GetFileName(theEntry.Name);

                // create directory
                if (!string.IsNullOrEmpty(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (fileName != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(theEntry.Name))
                    {

                        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;
                            }
                        }
                    }
                }
            }
        }
    }
}

 

2、 指定文件及其壓縮文件目錄配置在 ZipFileConfig.xml 中。配置如下:

<?xml version="1.0" encoding="utf-8" ?>
<zipPaths>
  <zipPath id="1">
    <fp>d:</fp>
    <tp>d:a</tp>
  </zipPath>
  <zipPath id="2">
    <fp>d:wmsDbServiceLog</fp>
    <tp>d:Log</tp>
  </zipPath>
  <zipPath id="3">
    <fp>d:wmsLog</fp>
    <tp>d:Log</tp>
  </zipPath>
</zipPaths>
原文地址:https://www.cnblogs.com/kuangxiangnice/p/5020261.html