如何删除用C#创建的超过7天的文件夹



文件夹结构为年/月/日。例如,在"C:\folder\2022\09"中,有名为1到30的文件夹(因为8月份有30天(。同样,在接下来的几天里,每天都会创建一个文件夹,其名称将仅为当天的数字,例如今天创建的文件的"C:\folder\2022\09\19"。当我想用c#创建的"sample.exe"运行时,它将删除在过去7天之前创建的文件夹,并且不会接触在过去7天后创建的文件夹。我该怎么做?

我想这就是问题所在。

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

这个答案假设您是根据文件夹及其父文件夹的名称而不是文件夹的元数据来测量日期的。

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

string directoryPath = @"C:folder2022919";

如果你很懒,只想在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与DateTime.Now或任何其他实例进行比较。

只需使用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);

然后,您可以检查该日期是否比DateTime.Now晚7天,并使用Directory.Delete(folderPath);删除必要的文件夹

最新更新