.NET 批量替换关键字

最近nfx462的项目升级.NET6需要批量替换Ilogger为Ilogger<类名>
vs自带的搜索替换其正则表达式好像只能匹配一行,直接扫描文件替换吧
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
string path = "";
var files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories).ToList();
files = files.Where(x =>
{
    string[] arr = x.Split('\\');
    var fileName = arr[^1];
    return fileName.Count(c => c == '.') == 1 && !fileName.StartsWith('I');
}).ToList();

foreach (string filePath in files)
{
    string[] arr = filePath.Split('\\');
    var fileName = arr[^1].Substring(0, arr[^1].Length - 3);
    bool hasChange = false;
    if (File.Exists(filePath))
    {
        string[] lines = System.IO.File.ReadAllLines(filePath);
        for (int i = 0; i < lines.Length; i++)
        {
            if (lines[i].Contains("ILogger"))
            {
                hasChange = true;
                lines[i] = lines[i].Replace("ILogger", $"ILogger<{fileName}>");
            }
        }
        if (hasChange)
        {
            File.WriteAllLines(filePath, lines);
        }
    }
}
Console.ReadKey();

 



posted @ 2023-01-30 15:16  李修乐  阅读(57)  评论(0)    收藏  举报