删除那些比某些天数的文件 [英] Removing files that are older than some number of days

查看:78
本文介绍了删除那些比某些天数的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这是在做相当多的日志记录的应用相当普遍的要求。我工作的一个C#Windows应用程序,.NET 3.5。



我的应用程序生成万吨,其中有一个当前的日期放在文件名像这样20091112.日志文件是什么将删除旧不如说30天文件的最佳策略。
的一种方法,我要使用它,是要遍历文件名,提取日期部分,转换成DateTime对象,并与今天的日期进行比较。
是有一种优雅的正则表达式解决这个:)?或者更好的东西。


解决方案

  var中的文件=新的DirectoryInfo(@C:\?日志)的GetFiles(*日志)。 
的foreach(在文件var文件)
{
如果(DateTime.UtcNow - file.CreationTimeUtc> TimeSpan.FromDays(30))
{
File.Delete (file.FullName);
}
}


I guess this is a pretty common requirement in a application that does quite a bit of logging. I am working on a C# Windows application, .NET 3.5.

My app generates tons of log files which has a current date put in the file name like so 20091112. What would be the best strategy to remove files older than say 30 days. One approach I am about to use it, is to loop through the file names, extract the date part, convert into DateTime object and compare with today's date. Is there an elegant Regular Expression solution to this :) ? Or something better?

解决方案

var files = new DirectoryInfo(@"c:\log").GetFiles("*.log");
foreach (var file in files)
{
    if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(30))
    {
        File.Delete(file.FullName);
    }
}

这篇关于删除那些比某些天数的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆