如何根据文件名中嵌入的时间戳删除文件

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

我正在根据创建时间戳过滤要删除的文件。使用文件创建的代码段工作正常,只是这些文件嵌入了与创建时间不同的时间戳。这会导致一堆文件丢失而无法删除。

这是我目前正在使用的:

public static void DeleteLogFiles(string sPath, DateTime dtDate, int iLogFileRetention)
{
    try
    {
        (from f in new DirectoryInfo(sPath).GetFiles()
            where f.CreationTime < dtDate.Subtract(TimeSpan.FromDays(iLogFileRetention))
            select f
            ).ToList()
            .ForEach(f => f.Delete());
    }
    catch (Exception ex)
    {
    }
}

文件名中嵌入的时间戳格式为 MMddyyyyHHmmss。

ABCD_20240309000024.dat, but its last modified date is 03/12/2024

如何修改上面的 Linq 语句以使用嵌入时间戳而不是创建/修改日期?

where f.FileName ?????
c# linq delete-file
1个回答
0
投票

这未经测试,但我认为它应该可以完成工作:

var filePaths = from filePath in Directory.GetFiles(folderPath)
                where DateTime.TryParseExact(Path.GetFileNameWithoutExtension(filePath).Split('_').Last(),
                                             "MMddyyyyHHmmss",
                                             null,
                                             DateTimeStyles.None,
                                             out var creationTime) &&
                      creationTime < thresholdDate
                select filePath;

thresholdDate
是您应该在查询之前而不是在查询内计算一次的内容。您知道每个输入项都相同的任何内容都不应该在查询中计算。

© www.soinside.com 2019 - 2024. All rights reserved.