C# 磁盘清理(远程/本地)

本文介绍了一款用于远程及本地磁盘清理的工具,能够针对指定的文件类型和保留时间进行自动化清理工作。该工具利用C#编程语言,并通过WMI(Windows Management Instrumentation)实现对远程计算机的文件管理和删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值