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. YTU 2437: C++ 习题 比较大小-类模板

    2437: C++ 习题 比较大小-类模板 时间限制: 1 Sec  内存限制: 128 MB 提交: 1144  解决: 805 题目描述 声明一个类模板,利用它分别实现两个整数.浮点数和字符的比较 ...

  2. Java 并发 —— 读写锁(ReadWriteLock)

    读写锁(ReadWriteLock),顾名思义,就是在读写某文件时,对该文件上锁. 1. ReentrantReadWriteLock 三部曲: 加锁: 读写操作: 解锁:(为保证解锁操作一定执行,通 ...

  3. 并不对劲的图论专题(三):SPFA算法的优化

    1.bzoj1489-> 这是个新套路. 我们希望找到最小的x,那么可以二分x,然后判断是否存在圈的边权的平均值小于等于x. 设圈的边权依次为w1,w2,w3,…,wk,平均值为p, 则有p= ...

  4. linux上用mplayer播放264文件

    Linux上,264视频裸码流可用mplayer进行播放. 同时,可用-fps参数控制帧率. 参考:http://www.chinavideo.org/archiver/?tid-16088.html

  5. 利用动态扫描和定时器1在数码管上显示出从765432开始以1/10秒的速度往下递减 直至765398并保持此数,与此同时利用定时器0以500MS速度进行流水灯从上至下移动 ,当数码管上数减到停止时,实验板上流水灯出停止然后全部开始闪烁,3秒后(用 T0定时)流水灯全部关闭,数码管上显示出“HELLO”,到此保持住

    #include <reg52.h> #include <intrins.h> #define uchar unsigned char #define uint unsigne ...

  6. SpringMVC Model,ModelMap ModelAndView

    SpringMVC 调用方法之前会创一个隐含的模型对象(即Model,ModelMap ModelAndView) //@ModelAttribute 先于login方法执行 @ModelAttrib ...

  7. Unix\Linux | 总结笔记 | man帮助

    0.目录 手册页分类说明 man手册中的段落说明     1.  man手册页分类 man1  普通用户可以执行的命令帮助 man2  系统调用.内核函数的说明帮助 man3   库函数说明帮助 ma ...

  8. flask请求访问数据

    flask请求访问数据 在flask框架中,访问请求数据由全局的request对象来提供,在flask框架中,request对象具有 全局作用域: from flask import request ...

  9. 数论 HDOJ 5407 CRB and Candies

    题目传送门 题意:求LCM (C(N,0),C(N,1),...,C(N,N)),LCM是最小公倍数的意思,C函数是组合数. 分析:先上出题人的解题报告 好吧,数论一点都不懂,只明白f (n + 1) ...

  10. 应用交付、负载均衡(Load balancing)、高可用、F5

    “应用交付”,实际上就是指应用交付网络(Application Delivery Networking,简称ADN),它利用相应的网络优化/加速设备,确保用户的业务应用能够快速.安全.可靠地交付给内部 ...