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的 ...
随机推荐
- fcitx-configtool
配置输入法
- Where Are You Standing?
/*********************************************************************** * Where Are You Standing? * ...
- win7下IIS7.0虚拟目录不存在的问题
问题:在IIS7.0下选中虚拟目录,右边浏览应用程序下,自动打开浏览器找开虚拟目录下的网站,但过一会什么都没有改变,再一次右边浏览应用程序,就提示 “虚拟目录不存在”. 解决方法:右键网站或下面的虚拟 ...
- 关于jenkins的安装及自动部署
1. 安装Jenkins 1.1 准备Linux服务器, 关闭防火墙禁止开机启动 systemctl stop firewalld.service #停止firewall systemctl disa ...
- 【WIP】rails redis的使用
创建: 2018/03/17 [任务表]TODO 注: mac版 %开头表示命令行命令 安装 安装 % brew install redis 确认版本 % redis-server --ver ...
- Postgresql个人维护库时,出现有用户在连接又找不到这个用户是谁的强制中断连接的方法;
方法一: 去PostgreSQL目录下/data/pgdata/9.4,找到pg_hba.conf, 修改pg_hba.conf的白名单IP (修改前,最好服务已停止,我是这么操作的) # IPv4 ...
- idea运行scala有问题
报这个错误:java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)Lscala/collection/m ...
- bzoj 4555: [Tjoi2016&Heoi2016]求和【NTT】
暴力推式子推诚卷积形式,但是看好多blog说多项式求逆不知道是啥.. \[ \sum_{i=0}^{n}\sum_{j=0}^{n}S(i,j)*2^j*j! \] \[ S(i,j)=\frac{1 ...
- P4323 [JSOI2016]独特的树叶(树哈希)
传送门 树哈希?->这里 反正大概就是乱搞--的吧-- //minamoto #include<bits/stdc++.h> #define R register #define l ...
- SELinux的启动和关闭
1.SELinux简介 SELinux是Security Enhanced Linux的缩写,字面上的意思就是安全强化的Linux,它是由美国国家安全局 (NSA) 开发的,整合到Linux核心的一个 ...