windows 文件清理工具

磁盘不够大,备份文件每天都生成,大概半个月就得手工清理一次,基于此,花了点时间写了个简单文件清理工具

采用WinForm 4.6.1实现,页面上需要拖放一个TextBox 控件

1、配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
	</startup>
	<appSettings>
		<!--清理的路径 -->
		<add key="TargetPath" value="D:\\Test" />
		<!--清除超过该天数的文件-->
		<add key="ClearInterval" value="20"/>
		<!--执行间隔-小时-->
		<add key="ExceteInterval" value="12"/>
	</appSettings>
</configuration>

  

2、全局错误处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileClearTools
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FileClear());
            }
            catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //LogManager.WriteLog(str);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //LogManager.WriteLog(str);
        }

        /// <summary>
        /// 生成自定义异常消息
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="backStr">备用异常消息:当ex为null时有效</param>
        /// <returns>异常字符串文本</returns>
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】:" + ex.GetType().Name);
                sb.AppendLine("【异常信息】:" + ex.Message);
                sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】:" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }
    }
}
View Code

3、主要实现代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace FileClearTools
{
    /// <summary>
    /// 功能描述:文件定时清理工具
    /// 创建者:hewj
    /// 创建时间:2021.07.14
    /// -------------修改记录--------------
    /// 2021.07.14  hewj  创建
    /// </summary>
    public partial class FileClear : Form
    {
        private static System.Timers.Timer _aTimer;
        /// <summary>
        /// 检测路径
        /// </summary>
        private string[] _targetPaths;
        /// <summary>
        /// 清理文件间隔(天)
        /// </summary>
        private int _clearInterval;
        /// <summary>
        /// 执行间隔(小时)
        /// </summary>
        private int _txceteInterval;
        private Queue<string> _msgQueue = new Queue<string>();
        public FileClear()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
            txtMsg.TextChanged += txtMsg_TextChanged;
            txtMsg.ReadOnly = true;
        }

        private void FileClear_Load(object sender, EventArgs e)
        {
            ReaderConfiguration();
            SetTimer();
            WriteToText();
        }

        private void ReaderConfiguration()
        {
            WriteLog("读取配置...");
            var path = ConfigurationManager.AppSettings["TargetPath"];
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("未找到AppSetting配置:TargetPath");
            }
            _targetPaths = path.Split(new char[] { ';' });
            var clearDasy = ConfigurationManager.AppSettings["ClearInterval"];
            if (string.IsNullOrEmpty(clearDasy))
            {
                throw new Exception("未找到AppSetting配置:ClearInterval");
            }
            _clearInterval = int.Parse(clearDasy);
            var interval = ConfigurationManager.AppSettings["ExceteInterval"];
            if (string.IsNullOrEmpty(interval))
            {
                throw new Exception("未找到AppSetting配置:TxceteInterval");
            }
            _txceteInterval = int.Parse(interval);
            WriteLog($"清理路径:{path}");
            WriteLog($"清理过期天数:{clearDasy}天");
            WriteLog($"执行时间间隔:{interval}小时");
        }

        private void SetTimer()
        {
            var time = _txceteInterval * 60 * 60 * 1000;
            // Create a timer with a two second interval.
            _aTimer = new System.Timers.Timer(time);
            // Hook up the Elapsed event for the timer. 
            _aTimer.Elapsed += OnTimedEvent;
            _aTimer.AutoReset = true;
            _aTimer.Enabled = true;
        }

        private void WriteLog(string msg)
        {
            var m = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ")}" + msg;
            txtMsg.Text += m + System.Environment.NewLine;
            _msgQueue.Enqueue(m);
        }

        private void WriteToText()
        {
            var dir = System.Environment.CurrentDirectory;
            var path = $"{dir}\\log";
            var fileName = $"{path}\\{DateTime.Now.ToString("yyyy-MM-dd")}.txt";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            try
            {

                //创建写入流
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    while (_msgQueue.Count > 0)
                    {
                        sw.WriteLine(_msgQueue.Dequeue());
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fs.Close();
            }

        }

        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            for (int i = 0; i < _targetPaths.Length; i++)
            {
                var path = _targetPaths[i];
                DirectoryInfo root = new DirectoryInfo(path);
                var dirs = root.GetDirectories();
                foreach (var item in dirs)
                {
                    TimeSpan sp = DateTime.Now.Subtract(item.LastWriteTime);
                    if (sp.Days > _clearInterval)
                    {
                        WriteLog($"delete {item.FullName}");
                        item.Delete(true);
                    }
                }
                if (dirs.Length == 0)
                {
                    WriteLog($"路径:{path}没有需要清理的文件");
                }
            }
            WriteToText();
        }

        private void txtMsg_TextChanged(object sender, EventArgs e)
        {
            this.txtMsg.Focus();//获取焦点
            this.txtMsg.Select(this.txtMsg.TextLength, 0);//光标定位到文本最后
            this.txtMsg.ScrollToCaret();//滚动到光标处
        }


    }
}
View Code

 

posted @ 2021-07-14 13:43  <渔人>  阅读(120)  评论(0编辑  收藏  举报