如何使用 C# 删除过去 7 天之前创建的文件夹?

问题描述 投票:0回答:4

文件夹结构为年/月/日。例如,在“C:older�2 9”中,有名为 1 到 30 的文件夹(因为 8 月有 30 天)。同样,在接下来的几天里,每天都会创建一个文件夹,其名称将仅为当天的编号,例如“C:older�2 9 9”表示今天创建的文件。 当我想用 c# 创建的“sample.exe”运行时,它将删除过去 7 天之前创建的文件夹,并且不会触及过去 7 天创建的文件夹。我怎样才能做到这一点?

c# directory exists
4个回答
1
投票

我认为就是这样。

int limit = 7;

foreach (string dir in Directory.GetDirectories(yourPath))
{
   DateTime createdTime = new DirectoryInfo(dir).CreationTime;
   if (createdTime < DateTime.Now.AddDays(-limit))
   {
       Directory.Delete(dir);
    }
 }

0
投票

此答案假设您正在根据文件夹及其父级的名称来测量日期,而不是文件夹的元数据。

收集所有可能要删除的文件夹的列表,并获取完整路径。

string directoryPath = @"C:\folder\2022\09\19";

如果你很懒并且只想在 Windows 上运行,请用反斜杠分隔。

string[] pathSegments = directoryPath.Split('\\');

最后一个元素代表日期。倒数第二个代表月份,倒数第三个代表年份。然后,您可以使用该信息构造您自己的 DateTime 对象。

DateTime pathDate = new DateTime(
    year: int.Parse(pathSegments[^3]),
    month: int.Parse(pathSegments[^2]),
    day: int.Parse(pathSegments[^1])
);

您现在可以轻松地将此日期时间与

DateTime.Now
或任何其他实例进行比较。


0
投票

如果你只是删除目录,你可能会得到一个异常,里面仍然有文件。如果您想删除该文件夹,无论它是否为空,请先清理该目录,检查它是否为空,然后将其删除。

DateTime oldDate = DateTime.Now.AddDays(-7); 
foreach (string dir in System.IO.Directory.GetDirectories(yourPath))
{
   DirectoryInfo dirInfo = new DirectoryInfo(dir);
   DateTime createdTime = dirInfo.CreationTime;
   if (createdTime < oldDate)
   {
        foreach (String file in System.IO.Directory.GetFiles(dirInfo.FullName))
        {
            FileInfo fi = new FileInfo(file);
            if (fi.LastWriteTime < oldDate)  
            {
                fi.Delete();
            }
        }
        //Now check if safe to remove the folder
        var x = dirInfo.EnumerateFiles("*.*");
        if (x.Count() == 0)
        {
            System.IO.Directory.Delete(dir);
        }
   }
}

-1
投票

只需使用

Directories.GetDirectories(yourPath)
获取文件夹名称,然后解析文件夹名称。 您可以使用
string[] date = String.Split('\\')
然后使用

int year = date[0];
int month = date[1];
int day = date[2];
DateTime folderDate = new DateTime(year, month, day);

然后您可以检查该日期是否晚了 7 天

DateTime.Now
并使用
Directory.Delete(folderPath);

删除必要的文件夹
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.