You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中使用两个日期选择器筛选文件夹中的.txt日志文件

筛选指定日期范围内的日志文件

核心思路

  1. 遍历目标目录:获取所有.txt格式的日志文件
  2. 提取日期标识:从文件名中匹配出ddMMyyyy格式的8位日期字符串
  3. 解析日期:将提取的字符串转换为标准DateTime类型,避免格式混淆
  4. 范围对比:将文件日期与两个DateTimePicker选择的日期范围做对比,筛选符合条件的文件

代码实现(C# WinForms为例)

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

public class LogFilterHelper
{
    // 获取指定日期范围内的日志文件路径
    public static List<string> FilterLogsByDateRange(string logDirectory, DateTime startDate, DateTime endDate)
    {
        var matchedFiles = new List<string>();
        // 正则匹配文件名中的ddMMyyyy格式日期(针对示例文件名优化,匹配Logs_后的8位数字)
        var dateRegex = new Regex(@"Logs_(\d{8})");

        foreach (var filePath in Directory.GetFiles(logDirectory, "*.txt"))
        {
            var fileName = Path.GetFileName(filePath);
            var regexMatch = dateRegex.Match(fileName);

            if (regexMatch.Success && DateTime.TryParseExact(regexMatch.Groups[1].Value, "ddMMyyyy", null, System.Globalization.DateTimeStyles.None, out DateTime fileDate))
            {
                // 仅对比日期部分,忽略时间
                var fileDateOnly = fileDate.Date;
                var startDateOnly = startDate.Date;
                var endDateOnly = endDate.Date;

                if (fileDateOnly >= startDateOnly && fileDateOnly <= endDateOnly)
                {
                    matchedFiles.Add(filePath);
                }
            }
        }

        return matchedFiles;
    }

    // WinForms界面调用示例(按钮点击事件)
    private void btnFilterLogs_Click(object sender, EventArgs e)
    {
        // 替换为你的日志目录路径
        string targetDir = @"D:\BlockPanelLogs";
        DateTime rangeStart = dtpStartDate.Value;
        DateTime rangeEnd = dtpEndDate.Value;

        var filteredLogs = FilterLogsByDateRange(targetDir, rangeStart, rangeEnd);

        // 将结果展示到ListBox
        listBoxFilteredLogs.Items.Clear();
        foreach (var logPath in filteredLogs)
        {
            listBoxFilteredLogs.Items.Add(Path.GetFileName(logPath));
        }
    }
}

关键注意事项

  • 正则精准性:如果文件名中存在其他8位数字,建议针对性调整正则(比如示例中的Logs_(\d{8})),避免误提取无关数字
  • 日期解析容错:必须指定ddMMyyyy格式解析,防止系统默认格式(如MMddyyyy)解析错误
  • 边界控制:代码中包含起始和结束当天的文件,若需排除边界,可将>=/<=改为>/<

内容的提问来源于stack exchange,提问作者shanuka_payoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:51:02