using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Text;
namespace SYS_TEST.OtherClass
{
//磁盘清理(远程/本地)
//需要引用System.Management.dll
public class RemoteAutoCleaning
{
private int holdtime = 7;
private string ip = "", fileType = "", strMsg = "";
public void ThreadRun()
{
strMsg = "";
string strHostName = Dns.GetHostName();//取得本机的主机名
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);//取得本机IP
string localip = ipEntry.AddressList[0].ToString();//假设本地主机为单网卡,取得第一个IP
DataSet ds = new DataSet();//此处需要自行绑定需要监控的ip数据集
//循环遍历IP目录
foreach (DataRow dr in ds.Tables[0].Rows)
{
try
{
ip = dr["ip"].ToString().Trim();
fileType = "";
holdtime = 7;
string strpath = dr["directory"].ToString().Trim();//文件夹目录
string strdisk = strpath.Substring(0, 2);//物理磁盘
string strlist = "\\\\" + strpath.Substring(3, strpath.Length - 3).Replace(@"\", @"\\") + "\\\\%";//磁盘目录
if (dr["filetype"].ToString().Trim() != "")
{
fileType = dr["filetype"].ToString().Trim(); //文件类型
}
if (dr["savetime"].ToString().Trim() != "0")
{
holdtime = int.Parse(dr["savetime"].ToString().Trim()); //保留天数
}
if (ip == localip)
{
#region 本机
DirectoryInfo directory = new DirectoryInfo(strpath);
ClearLocalDirectory(directory);
#endregion
}
else
{
#region 远程
bool filecheck = false;
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = "Administrator";
connectionOptions.Password = "password";
connectionOptions.Timeout = new TimeSpan(1, 1, 1, 1);//连接时间
//ManagementScope 的服务器和命名空间。
string path = string.Format("\\\\{0}\\root\\cimv2", ip);
ManagementScope scope = new ManagementScope(path, connectionOptions);
scope.Connect();
//验证目录是否配置错误
string strQuerys = string.Format("select * from CIM_DataFile where (Extension='dll' or Extension='exe') and Drive = '{0}' and Path like '{1}'", strdisk, strlist);
ObjectQuery querys = new ObjectQuery(strQuerys);
ManagementObjectSearcher searchers = new ManagementObjectSearcher(scope, querys);
foreach (ManagementObject ms in searchers.Get())
{
strMsg += ip + " " + strpath + "目录中含有.dll,.exe等文件时,可能是配置错误,无法删除此目录下的文件" + System.Environment.NewLine;
filecheck = true;
break;
}
if (filecheck)
{
continue;
}
//查询目录下的文件信息
string strQuery = string.Format("select * from CIM_DataFile where Drive = '{0}' and Path like '{1}'", strdisk, strlist);
ObjectQuery query = new ObjectQuery(strQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject m in searcher.Get())
{
string s = m["Name"].ToString().Trim().ToUpper();
string str = m["CreationDate"].ToString().Trim().Substring(0, 8);
IFormatProvider ifp = new CultureInfo("zh-CN", true);
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", ifp);
if (!isInTimeRange(holdtime, dt))
{
if (fileType != "")
{
if (s.EndsWith("." + fileType))
{
m.Delete();
}
}
else
{
m.Delete();
}
}
}
#endregion
}
}
catch { }
}
}
/// <summary>
/// 本机磁盘清理
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private void ClearLocalDirectory(DirectoryInfo directory)
{
FileInfo[] allFile = directory.GetFiles();
foreach (FileInfo fi in allFile)
{
string fileName = fi.Name.Trim().ToUpper();
DateTime creationtime = fi.CreationTime;
if (!isInTimeRange(holdtime, creationtime))
{
if (fileName.EndsWith(".DLL") || fileName.EndsWith(".EXE"))
{
strMsg += ip + " " + fi.DirectoryName + "目录中含有.dll,.exe等文件时,可能是配置错误,无法删除" + System.Environment.NewLine;
break;
}
else
{
if (fileType != "")
{
if (fi.Name.EndsWith("." + fileType))
{
fi.Delete();
}
}
else
{
fi.Delete();
}
}
}
}
DirectoryInfo[] allDir = directory.GetDirectories();
foreach (DirectoryInfo d in allDir)
{
ClearLocalDirectory(d);
}
}
/// <summary>
/// 是否在时间范围内
/// </summary>
/// <param name="timeRange"></param>
/// <param name="creatTime"></param>
/// <returns></returns>
private bool isInTimeRange(int timeRange, DateTime creatTime)
{
DateTime dtNow = DateTime.Now;
TimeSpan span = dtNow.Subtract(creatTime);
if (span.TotalDays.CompareTo(Convert.ToDouble(timeRange)) > 0) //默认设置7天
{
return false;
}
return true;
}
}
}
C# 磁盘清理(远程/本地)
最新推荐文章于 2024-05-20 13:09:01 发布