windows 文件清理工具

2021-07-14 21:03

阅读:600

标签:错误   sha   build   close   pen   ring   实现   线程   清理工具   

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

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

1、配置文件:

  

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
    {
        /// 
        /// 应用程序的主入口点。
        /// 
        [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);
        }

        /// 
        /// 生成自定义异常消息
        /// 
        /// 异常对象
        /// 备用异常消息:当ex为null时有效
        /// 异常字符串文本
        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
{
    /// 
    /// 功能描述:文件定时清理工具
    /// 创建者:hewj
    /// 创建时间:2021.07.14
    /// -------------修改记录--------------
    /// 2021.07.14  hewj  创建
    /// 
    public partial class FileClear : Form
    {
        private static System.Timers.Timer _aTimer;
        /// 
        /// 检测路径
        /// 
        private string[] _targetPaths;
        /// 
        /// 清理文件间隔(天)
        /// 
        private int _clearInterval;
        /// 
        /// 执行间隔(小时)
        /// 
        private int _txceteInterval;
        private Queuestring> _msgQueue = new Queuestring>();
        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 )
            {
                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

 

windows 文件清理工具

标签:错误   sha   build   close   pen   ring   实现   线程   清理工具   

原文地址:https://www.cnblogs.com/heweijian/p/15010425.html

上一篇:HTML5复习

下一篇:k8s API Server 原理分析


评论


亲,登录后才可以留言!