C#定时删除多余文件

文件一直不断生成,所以增加一个定时删除文件的功能

		 /// <summary>
        /// 定时删除文件线程
        /// </summary>
 		private void DeleteFileThreadStart()
        {
            new Thread(()=> 
            {
                while (true)
                {
                    DeleteOverFile();
                    Thread.Sleep(1000 * 60 * 60 * 10);
                }
            }) { IsBackground = true }.Start();
        }


        /// <summary>
        /// 删除过期文件
        /// </summary>
        private void DeleteOverFile()
        {
            try
            {

                int HowManyDays = 7;  //超过多少天删除
                string fileFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"\Logs";
                DirectoryInfo theFolder = new DirectoryInfo(fileFolderPath);
                FileInfo[] fileInfo = theFolder.GetFiles();
                foreach (FileInfo NextFile in fileInfo)
                {
                    if (NextFile.Extension != ".log") continue;
                    if (int.Parse(DateTime.Now.AddDays(-HowManyDays).ToString("yyyyMMdd")) >= int.Parse(NextFile.CreationTime.ToString("yyyyMMdd")))
                    {
                        File.Delete(fileFolderPath + string.Format(@"\\{0}", NextFile));
                    }
                }

            }
            catch (Exception e)
            {
              
            }
        }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在.NET中,我们可以使用Timer类来定时删除文件。 首先,我们需要引入System.IO命名空间,这样我们可以使用文件操作相关的类和方法。 接下来,我们可以创建一个Timer对象,并设置其间隔时间和触发删除文件的事件处理方法。例如,可以将间隔时间设置为24小时,即每天执行一次删除文件的操作。 在事件处理方法中,我们需要指定要删除文件的路径和名称。使用File类的Delete方法,可以删除指定文件。例如,可以使用以下代码删除名为"example.txt"的文件: ```C# // 设置文件路径和名称 string filePath = "C:\\example.txt"; // 删除文件 File.Delete(filePath); ``` 最后,我们需要启动定时器,使其开始工作。可以使用Timer的Start方法来启动定时器。 完整的代码示例如下所示: ```C# using System; using System.IO; namespace FileDeletion { class Program { static void Main(string[] args) { // 设置文件路径和名称 string filePath = "C:\\example.txt"; // 创建定时器对象,设置间隔时间为24小时 Timer timer = new Timer(24 * 60 * 60 * 1000); // 设置定时器触发事件处理方法 timer.Elapsed += (sender, e) => DeleteFile(filePath); // 启动定时器 timer.Start(); // 防止控制台应用程序在完成工作之终止 Console.ReadLine(); } static void DeleteFile(string filePath) { // 删除文件 File.Delete(filePath); } } } ``` 这样,每隔24小时,定时器就会调用删除文件的方法,实现了定时删除文件的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值