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

如何将C#日志匹配结果存入集合/字符串,循环外输出并用于邮件告警?

修改后的代码实现
static void Main(string[] args)
{
    string rootPath = @"C:\Logs";
    var files = Directory.GetFiles(rootPath, "*.log*", SearchOption.AllDirectories);
    // 用列表存储所有匹配结果,方便后续用于邮件告警
    List<string> errorResults = new List<string>();

    foreach (string file in files)
    {
        // 使用using语句自动释放StreamReader资源,无需手动Close
        using (StreamReader myReader = new StreamReader(file))
        {
            string line;
            while ((line = myReader.ReadLine()) != null)
            {
                if (line.Contains("result=[false]"))
                {
                    // 优化:只拆分一次字符串,避免重复操作
                    string[] lineParts = line.Split(' ');
                    string datetime = $"{lineParts[0]} {lineParts[1]}";
                    string tablename = lineParts[3];

                    string resultLine = $"Date : {datetime} -- Table : {tablename} ";
                    // 将结果存入列表,而非即时打印
                    errorResults.Add(resultLine);
                }
            }
        }
    }

    // 循环外统一输出所有结果
    foreach (string result in errorResults)
    {
        Console.WriteLine(result);
    }

    // 若需拼接成单个字符串用于邮件正文:
    string emailContent = string.Join(Environment.NewLine, errorResults);
    // 后续可将emailContent传入邮件发送逻辑

    Console.ReadLine();
}
关键修改说明
  • 在所有循环外部声明List<string> errorResults,专门存储所有匹配到的错误行信息
  • 把原有的Console.WriteLine(line)替换为errorResults.Add(resultLine),将结果存入列表而非即时打印
  • 用using语句包裹StreamReader,自动管理资源释放,替代手动调用Close()
  • 优化字符串拆分逻辑,仅执行一次Split操作,提升代码运行效率
  • 最后可直接遍历列表输出结果,或通过string.Join拼接成完整字符串,直接作为邮件告警的正文内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:54:45