C# 使用 .NET 删除目录中超过 3 个月的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2222348/
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-07 00:31:02  来源:igfitidea点击:

Delete files older than 3 months old in a directory using .NET

c#.netfiledirectory

提问by JL.

I would like to know (using C#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible.

我想知道(使用 C#)如何删除某个目录中超过 3 个月的文件,但我想日期期限可能是灵活的。

Just to be clear: I am looking for files that are older than 90 days, in other words files created less than 90 days ago should be kept, all others deleted.

需要明确的是:我正在寻找超过 90 天的文件,换句话说,应该保留少于 90 天前创建的文件,删除所有其他文件。

采纳答案by Steve Danner

Something like this outta do it.

像这样的事情不能做。

using System.IO; 

string[] files = Directory.GetFiles(dirName);

foreach (string file in files)
{
   FileInfo fi = new FileInfo(file);
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
      fi.Delete();
}

回答by Keith Bloom

The GetLastAccessTimeproperty on the System.IO.File class should help.

GetLastAccessTime上有System.IO.File类属性应该有所帮助。

回答by Ian Jacobs

Basically you can use Directory.Getfiles(Path) to get a list of all the files. After that you loop through the list and call GetLastAccessTim() as Keith suggested.

基本上你可以使用 Directory.Getfiles(Path) 来获取所有文件的列表。之后,您遍历列表并按照 Keith 的建议调用 GetLastAccessTim()。

回答by nWorx

you just need FileInfo-> CreationTime

你只需要FileInfo-> CreationTime

and than just calculate the time difference.

而不仅仅是计算时差。

in the app.config you can save the TimeSpanvalue of how old the file must be to be deleted

在 app.config 中,您可以保存文件必须被删除的时间跨度

also check out the DateTime Subtractmethod.

还可以查看DateTime Subtract方法。

good luck

祝你好运

回答by Pierre-Luc Champigny

Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):

以下是如何获取目录中文件的创建时间并查找 3 个月前(准确地说是 90 天前)创建的文件的片段:

    DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);

    // Get info of each file into the directory
    foreach (FileInfo fi in source.GetFiles())
    {
        var creationTime = fi.CreationTime;

        if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
        {
            fi.Delete();
        }
    }

回答by jinsungy

Alternatively, you can use the File.GetCreationTime Methodif you need to delete files based on creation dates.

或者,如果您需要根据创建日期删除文件,您可以使用File.GetCreationTime 方法

回答by Samuel Neff

For those that like to over-use LINQ.

对于那些喜欢过度使用 LINQ 的人。

(from f in new DirectoryInfo("C:/Temp").GetFiles()
 where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
 select f
).ToList()
    .ForEach(f => f.Delete());

回答by Uri Abramson

Here's a 1-liner lambda:

这是一个单行 lambda:

Directory.GetFiles(dirName)
         .Select(f => new FileInfo(f))
         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
         .ToList()
         .ForEach(f => f.Delete());

回答by Yiannis Leoussis

Something like that

类似的东西

            foreach (FileInfo file in new DirectoryInfo("SomeFolder").GetFiles().Where(p => p.CreationTime < DateTime.Now.AddDays(-90)).ToArray())
                File.Delete(file.FullName);

回答by vishal

            system.IO;

             List<string> DeletePath = new List<string>();
            DirectoryInfo info = new DirectoryInfo(Server.MapPath("~\TempVideos"));
            FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
            foreach (FileInfo file in files)
            {
                DateTime CreationTime = file.CreationTime;
                double days = (DateTime.Now - CreationTime).TotalDays;
                if (days > 7)
                {
                    string delFullPath = file.DirectoryName + "\" + file.Name;
                    DeletePath.Add(delFullPath);
                }
            }
            foreach (var f in DeletePath)
            {
                if (File.Exists(F))
                {
                    File.Delete(F);
                }
            }

use in page load or webservice or any other use.

用于页面加载或网络服务或任何其他用途。

My concept is evrry 7 day i have to delete folder file without using DB

我的概念是 evrry 7 天我必须在不使用 DB 的情况下删除文件夹文件