標簽:錯誤 sha build close pen ring 實現 線程 清理工具
磁盤不夠大,備份文件每天都生成,大概半個月就得手工清理一次,基于此,花了點時間寫了個簡單文件清理工具
采用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(); } } }
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();//滾動到光標處 } } }
標簽:錯誤 sha build close pen ring 實現 線程 清理工具
原文地址:https://www.cnblogs.com/heweijian/p/15010425.html