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:\WMS\Grocery\ZipFileConfig.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 > )
{
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 - ] != 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 - ] != 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 - ] != 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(); // 压缩级别 0-9
//s.Password = "123"; //Zip压缩文件密码
byte[] buffer = new byte[]; //缓冲区大小
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, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
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 = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
}
}
}
}
}
}

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

<?xml version="1.0" encoding="utf-8" ?>
<zipPaths>
<zipPath id="1">
<fp>d:\b</fp>
<tp>d:\a</tp>
</zipPath>
<zipPath id="2">
<fp>d:\wms\DbService\Log</fp>
<tp>d:\Log</tp>
</zipPath>
<zipPath id="3">
<fp>d:\wms\Log</fp>
<tp>d:\Log</tp>
</zipPath>
</zipPaths>

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

  1. resin-pro-4.0.34 服務器在windows环境下的配置

    resin-pro-4.0.34 服務器在windows环境下的配置(轉載请注明作者:icelong) 到caucho網站上http://www.caucho.com/download/下載resin ...

  2. PowerBI分析Exchange服務器IIS運行日誌

    PowerBI分析Exchange服務器IIS運行日誌 啟用狀態 PowerBI分析Exchange服務器IIS運行日誌 那麼在C:\inetpub\logs\LogFiles目錄下您才會看到如下日誌 ...

  3. windows上開啟多個apache服務器

    1.安裝apache(這裡我用的是集成環境) 比較php版本 5.6  與 7.2 比較mysql版本 拓展: 注意:對個不同的版本的mysql,命令行進入,需要指明端口號,如:mysql -uroo ...

  4. 創建HTTP 服務器

    var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res ...

  5. html5 服務器發送事件

    html5允許頁面獲得來自服務器的更新. 單項消息傳送: 頁面獲得服務器的更新. 以前頁面也可以獲得服務器的更新,但必須詢問服務器是否有可用的更新,而服務器發送事件是單向自動發送. 使用服務器發送事件 ...

  6. Jexus 強勁、堅固、免費、易用的Linux ASP.NET服務器

    Jexus 強勁.堅固.免費.易用的Linux ASP.NET服務器 Jexus是一款Linux平台上的高性能WEB服务器和负载均衡网关,以支持ASP.NET.ASP.NET CORE.PHP为特色, ...

  7. samba服務器下文件夾chmod權限技巧

    需要的效果: samba下文件夹(abc)不可以被重命名.不可以被刪除,其所有子目录可读可写. 如何做到: chmod 777 -R abc   # -R 使得abc下所有数据继承可读可写权限 chm ...

  8. 2019.11.29 SAP SMTP郵件服務器配置 發送端 QQ郵箱

    今天群裏的小夥伴問了如何配置郵件的問題,隨自己在sap裏面配置了一個 1.    RZ10配置參數 a)       参数配置前,先导入激活版本 执行完毕后返回 b)      输入参数文件DEFAU ...

  9. io.js的服務器突破

    Node.js与io.js那些事儿 InfoQ中文站 05月20日 14:26 去年12月,多位重量级Node.js开发者不满Joyent对Node.js的管理,自立门户创建了io.js.io.js的 ...

随机推荐

  1. bzoj2823: [AHOI2012]信号塔&&1336: [Balkan2002]Alien最小圆覆盖&&1337: 最小圆覆盖

    首先我写了个凸包就溜了 这是最小圆覆盖问题,今晚学了一下 先随机化点,一个个加入 假设当前圆心为o,半径为r,加入的点为i 若i不在圆里面,令圆心为i,半径为0 再重新从1~i-1不停找j不在圆里面, ...

  2. Hibernate、Spring和Struts2工作原理

    Hibernate.Spring和Struts2工作原理 博客分类: Java 基础 工作HibernateSpringMVCStruts  Hibernate.Spring和Struts2工作原理  ...

  3. Java 内存管理、JVM 工作原理与 Java 运行时系统

    Java 虚拟机规范中说明:所有的对象实例(all class instances)以及数组都要在堆上分配: the heap is the runtime data area from which ...

  4. Sleep示例分析

    sleep让"当前线程"由“运行状态”进入到“休眠(阻塞)状态”,sleep结束,线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行. 示例分析: pu ...

  5. Ruby  String类

    String类 更新: 2017/06/10 更新: 2017/06/23 puts()要空格可以直接不加参数 更新: 2017/08/17 增加rails引入的titleize 更新: 2017/1 ...

  6. 51nod 1238 最小公倍数之和 V3 【欧拉函数+杜教筛】

    首先题目中给出的代码打错了,少了个等于号,应该是 G=0; for(i=1;i<=N;i++) for(j=1;j<=N;j++) { G = (G + lcm(i,j)) % 10000 ...

  7. [SDOI2019] 移动金币

    分析 阶梯NIM模型:共有m+1堆石子,石子总数不超过n-m,求必胜的,即奇数堆石子数目异或和非零的局面数.补集转化,答案C(n,m)-奇数堆石子数目异或和位0的局面数. 可以想到按位dp,设f[i, ...

  8. Eclipse 最新版2018-09安装Maven教程

    其实在写这篇教程之前,花了不少时间来学习安装Maven.不是链接打不开,要么就是提供的方法不适合我这个版本,当然了,既然你能看到这篇教程说明我已经找到了正确方法. 打开Eclipse-Help-> ...

  9. Luogu P1541 乌龟棋 【线性dp】

    题目背景 小明过生日的时候,爸爸送给他一副乌龟棋当作礼物. 题目描述 乌龟棋的棋盘是一行 N 个格子,每个格子上一个分数(非负整数).棋盘第1格是唯一的起点,第 N 格是终点,游戏要求玩家控制一个乌龟 ...

  10. 用jdbc连接数据库并简单执行SQL语句

    一:版本一.这种存在一个问题就是每执行一次操作都会创建一次Connection链接和且释放一次链接 1:创建pojo对象(OR映射,一个pojo类对应一张数据库表)   package com.yin ...