C# 删除超过一定天数的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1720790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:14:53  来源:igfitidea点击:

Removing files that are older than some number of days

c#

提问by theraneman

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.

我想这是在进行大量日志记录的应用程序中非常常见的要求。我正在开发一个 C# Windows 应用程序,.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?

我的应用程序生成大量日志文件,这些文件的文件名中包含当前日期,例如 20091112。删除超过 30 天的文件的最佳策略是什么。我将要使用的一种方法是遍历文件名,提取日期部分,转换为 DateTime 对象并与今天的日期进行比较。是否有一个优雅的正则表达式解决方案:)?或者更好的东西?

采纳答案by Darin Dimitrov

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);
    }
}

回答by Konamiman

Substracting two DateTimeobjects will give you a TimeSpanobject, then you can just check its TotalDaysproperty. I can't think of anything simpler than this.

两个DateTime对象相减会得到一个TimeSpan对象,然后你可以检查它的TotalDays属性。我想不出比这更简单的事情了。

回答by bniwredyc

string directoryPath = "/log"; // your log directory path

foreach (string filePath in Directory.GetCreationTime(directoryPath))
{
    TimeSpan fileAge = File.GetLastWriteTime(filePath) - DateTime.Now;
    if (fileAge.Days > 30)
    {
        File.Delete(filePath);
    }
}

回答by yu_sha

As I understand, you want to use file name rather than modification time. Fine.

据我了解,您想使用文件名而不是修改时间。美好的。

Then the code is like this:

然后代码是这样的:

    foreach (string file in Directory.GetFiles(path))
    {
        string fileNameOnly=Path.GetFileNameWithoutExtension(file);
        DateTime fileDate = DateTime.ParseExact(fileNameOnly, "yyyyMMDD", CultureInfo.CurrentCulture);
        if (DateTime.Now.Subtract(fileDate).TotalDays > MaxDays)
            File.Delete(file);
    }

回答by Ruben Bartelink

[In PowerShell] you could paste the following into a PS1 file and make it part of an admin script if that suits:-

[在 PowerShell 中] 您可以将以下内容粘贴到 PS1 文件中,并使其成为管理脚本的一部分(如果合适):-

param($path=$(throw "Need to indicate path"), $daysToRetain=$(throw "Need to indicate how many days to retain"))

dir $path -r | ? { ([datetime]::UtcNow - $_.CreationTimeUtc).TotalDays -gt $daysToRetain } | del

param($path=$(throw "需要说明路径"), $daysToRetain=$(throw "需要说明保留多少天"))

目录 $path -r | ? { ([datetime]::UtcNow - $_.CreationTimeUtc).TotalDays -gt $daysToRetain } | 德尔

EDIT: And you can use -matchto parse the name if you feel using the file times isnt the right thing to do

编辑:-match如果您觉得使用文件时间不是正确的做法,您可以使用来解析名称

回答by PernerOl

update .net 4.0:

更新.net 4.0:

var files = new DirectoryInfo(directoryPath).GetFiles("*.log");
foreach (var file in files.Where(file => DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromHours(2))) {
     file.Delete();
}

回答by Neha Vishwakarma

string[] files = Directory.GetFiles(path);
foreach (string file in files)
 {
  if (File.GetLastWriteTime(file) < DateTime.Now.AddDays(-5))
    {
      File.Delete(file);
    }
 }