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:\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 過多,佔用過多硬盤空間,壓縮備份后節省空間資源的更多相关文章
- resin-pro-4.0.34 服務器在windows环境下的配置
resin-pro-4.0.34 服務器在windows环境下的配置(轉載请注明作者:icelong) 到caucho網站上http://www.caucho.com/download/下載resin ...
- PowerBI分析Exchange服務器IIS運行日誌
PowerBI分析Exchange服務器IIS運行日誌 啟用狀態 PowerBI分析Exchange服務器IIS運行日誌 那麼在C:\inetpub\logs\LogFiles目錄下您才會看到如下日誌 ...
- windows上開啟多個apache服務器
1.安裝apache(這裡我用的是集成環境) 比較php版本 5.6 與 7.2 比較mysql版本 拓展: 注意:對個不同的版本的mysql,命令行進入,需要指明端口號,如:mysql -uroo ...
- 創建HTTP 服務器
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res ...
- html5 服務器發送事件
html5允許頁面獲得來自服務器的更新. 單項消息傳送: 頁面獲得服務器的更新. 以前頁面也可以獲得服務器的更新,但必須詢問服務器是否有可用的更新,而服務器發送事件是單向自動發送. 使用服務器發送事件 ...
- Jexus 強勁、堅固、免費、易用的Linux ASP.NET服務器
Jexus 強勁.堅固.免費.易用的Linux ASP.NET服務器 Jexus是一款Linux平台上的高性能WEB服务器和负载均衡网关,以支持ASP.NET.ASP.NET CORE.PHP为特色, ...
- samba服務器下文件夾chmod權限技巧
需要的效果: samba下文件夹(abc)不可以被重命名.不可以被刪除,其所有子目录可读可写. 如何做到: chmod 777 -R abc # -R 使得abc下所有数据继承可读可写权限 chm ...
- 2019.11.29 SAP SMTP郵件服務器配置 發送端 QQ郵箱
今天群裏的小夥伴問了如何配置郵件的問題,隨自己在sap裏面配置了一個 1. RZ10配置參數 a) 参数配置前,先导入激活版本 执行完毕后返回 b) 输入参数文件DEFAU ...
- io.js的服務器突破
Node.js与io.js那些事儿 InfoQ中文站 05月20日 14:26 去年12月,多位重量级Node.js开发者不满Joyent对Node.js的管理,自立门户创建了io.js.io.js的 ...
随机推荐
- SWFObject 的基本使用方法
SWFObject是一个用于在HTML中方面插入Adobe Flash媒体资源(*.swf文件)的独立.敏捷的JavaScript模块.该模块中的JavaScript脚本能够自动检测PC.Mac机器上 ...
- 有向图强连通分量的Tarjan算法(转)
[有向图强连通分量] 在有向图G中,如果两个顶点间至少存在一条路径,称两个顶点强连通(strongly connected).如果有向图G的每两个顶点都强连通,称G是一个强连通图.非强连通图有向图的极 ...
- HDU4704:Sum(欧拉降幂公式)
Input 2 Output 2 Sample Input 2 由公式,ans=2^(N-1)%Mod=2^((N-1)%(Mod-1)+(Mod-1)) %Mod. 注意:降幂的之后再加一个Mod- ...
- [转]Python3 字典 items() 方法
原文Python3 字典 items()方法 描述 Python 字典 items() 方法以列表返回可遍历的(键, 值) 元组数组. 语法 items()方法语法: dict.items() 参数 ...
- word2vec中的数学原理(转)
- tyvj 1666 城市建设【最小生成树】
-Wall是个好东西,要不然我至死都看不出来我把(b[i]+b[j])写成了(b[i],b[j])-- 还是来自lyd的题解: (其实原来课件第一行式子写错了没有-1,然而我用sai手画了一个上去hh ...
- bzoj 1858: [Scoi2010]序列操作【线段树】
合并中间那块的时候没取max--WAWAWA 在线段树上维护一堆东西,分别是len区间长度,sm区间内1的个数,ll0区间从左开始最长连续0,ml0区间中间最长连续0,rl0区间从右开始最长连续0,l ...
- 基于ssh框架web示例
基于ssh框架web示例 介绍 Spring Boot Web 开发非常简单,该示例包括包括目前web开发基本都需要用到的内容 - 序列化(json)输出 - 过滤器(filters) - 监视器(l ...
- SpringMVC异步调用,Callable和DeferredResult的使用
Callable和DeferredResult都是springMVC里面的异步调用,Callable主要用来处理一些简单的逻辑,DeferredResult主要用于处理一些复杂逻辑 1.Callabl ...
- vi 和vim中的查找和替换
查找 命令模式输入 : /the-string-you-want-to-lookup 替换 命令模式输入 : s /from/to/