.NET 小案例 - 读取指定文件类型中关键词

73 阅读1分钟

需求

读取指定目录下指定格式的所有文件(aspx), 并检查文件中是否包含关键词,若未包含,则需要一一列出

环境搭建

在 C:\Users\Administrator\Desktop\Files 下船舰如下文件,其中1.aspx 和 2.aspx 包含关键词

2025-01-19_12-09-46.png

相关代码

using System.IO;
using System.Text;

const string FILE_PATH = "C:\\Users\\Administrator\\Desktop\\Files";
List<string> FILE_TYPES = new List<string> { "aspx" };

var log = new StringBuilder();
log.AppendLine($"{DateTime.Now.ToString("HH:mm:ss")}:");
log.AppendLine($"----------------------- START --------------------------");
try
{
    string[] files;
    try
    {
        files = Directory.GetFiles(FILE_PATH);
    }
    catch (Exception ex)
    {
        throw new Exception($"Load file path {FILE_PATH} fail.");
    }
   
    var errorList = new List<(string,string)>();

    for (int i = 0; i < files.Length; i++) {

        var filePath = files[i];
        foreach (var type in FILE_TYPES)
        {
            if (filePath.ToLower().EndsWith(type))
            {
                try
                {
                    string content = File.ReadAllText(filePath);
                    if (content.Contains("key"))
                    {
                        log.AppendLine($"{i + 1}. {filePath} √");
                    }
                    else
                    {
                        log.AppendLine($"{i + 1}. {filePath} ×");
                        errorList.Add((filePath, "The file does not contain keywords"));
                    }
                }
                catch (Exception ex)
                {
                    errorList.Add((filePath, ex.Message));
                }

            }
        }
    }
    log.AppendLine();

    if (errorList.Count >0){
        for (int i = 0; i < errorList.Count; i++)
        {
            log.AppendLine("----------------------- ERROR --------------------------");
            log.AppendLine($"[{i + 1}/{errorList.Count}] {errorList[i].Item1}: {errorList[i].Item2}");
        }
    }
    else
    {
        log.AppendLine("----------------------- ERROR ------------------------");
    }

    log.AppendLine("");
}
catch(Exception ex)
{
    log.AppendLine("----------------------- ERROR ------------------------");
    log.AppendLine($"Check fail: {ex.Message}");
    log.AppendLine();
    throw new Exception($"Checking files failed with the following error: {ex.Message}");
}
finally
{
    log.AppendLine($"----------------------- END -----------------------------");
    log.AppendLine();
    Console.WriteLine(log.ToString());
    string path = ".\\logs\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    string directory = Path.GetDirectoryName(path);
    if (!Directory.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }
    if (File.Exists(path))
    {
        File.AppendAllText(path, log.ToString());
    }
    else
    {
        File.WriteAllText(path, log.ToString());
    }
   
}

测试

成功筛选出指定格式的文件,并判断了是否包含关键词

2025-01-19_15-34-13.png

并在执行完毕后,将日志信息写入到文件中

2025-01-19_15-35-26.png