C# 批量替换文本文件里的内容

复制代码
void Main()
{
    var result = replaceFiles(@"C:\Users\admin\Desktop\opencv31\opencv\mybuild", "*.*", @"C:\Users\admin\Desktop\opencv31\opencv\mybuild", '\\'
        , new string[] { @"C:\Users\admin\Desktop\opencv31\opencv\mybuild\.vs" });
    result.Dump();
    result = replaceFiles(@"C:\Users\admin\Desktop\opencv31\opencv\mybuild", "*.*", @"C:\Users\admin\Desktop\opencv31\opencv\mybuild", '/'
        , new string[] { @"C:\Users\admin\Desktop\opencv31\opencv\mybuild\.vs" });
    result.Dump();
    result = replaceFiles(@"C:\Users\admin\Desktop\opencv31\opencv\mybuild", "*.*", @"C:\Users\admin\Desktop\opencv31\opencv", '\\'
        , new string[] { @"C:\Users\admin\Desktop\opencv31\opencv\mybuild\.vs" });
    result.Dump();
    result = replaceFiles(@"C:\Users\admin\Desktop\opencv31\opencv\mybuild", "*.*", @"C:\Users\admin\Desktop\opencv31\opencv", '/'
        , new string[] { @"C:\Users\admin\Desktop\opencv31\opencv\mybuild\.vs" });
    result.Dump();
}

List<string> replaceFiles(string dir, string extPattern, string find, char pathSeperator, string[] exceptDirectories)
{
    var result = new List<string>();
    
    if(exceptDirectories.Any(path=> path.ToUpper() == dir.ToUpper()))
        return result;
    
    var d = new DirectoryInfo(dir);
    foreach (var f in d.GetFiles())
    {
        if(!LikeOperator.LikeString(f.Extension, extPattern,CompareMethod.Text))
            continue;

        if(!isTextFile(f.FullName))
            continue;

        if (replaceFile(f.FullName, find, pathSeperator))
        {
            result.Add(f.FullName);
            f.FullName.Dump();
        }
    }

    foreach (var sd in d.GetDirectories())
        result.AddRange(replaceFiles(sd.FullName,extPattern,find, pathSeperator,exceptDirectories));
        
    return result;
}

bool replaceFile(string filepath, string find, char pathSeperator)
{
    find = find.Replace('\\', pathSeperator);
    find = find.Replace('/', pathSeperator);
    var content = File.ReadAllText(filepath);
    if (content.ToUpper().Contains(find.ToUpper()))
    {
        var path = new DirectoryInfo(filepath).Parent.FullName;
        path = path.Replace('\\', pathSeperator);
        path = path.Replace('/', pathSeperator);
        
        var pathPrefix = "";
        while (path.TrimEnd(pathSeperator).ToUpper() != find.TrimEnd(pathSeperator).ToUpper())
        {
            pathPrefix += @".." + pathSeperator;
            path = new DirectoryInfo(path).Parent.FullName;
            path = path.Replace('\\', pathSeperator);
            path = path.Replace('/', pathSeperator);
        }
        
        if(string.IsNullOrWhiteSpace(pathPrefix))
            pathPrefix = @"." + pathSeperator ;
        
        content = Regex.Replace(content, Regex.Escape(find), pathPrefix, RegexOptions.IgnoreCase);
        
        try
        {            
            File.WriteAllText(filepath,content);
        }
        catch (Exception ex)
        {
            ex.Message.Dump();
        }
        
        return true;
    }
        
    return false;
}

bool isTextFile(string fileName, int testSize = 100)
{
    var encoding = System.Text.Encoding.Default;
    using (var fileStream = File.OpenRead(fileName))
    {
        var rawData = new byte[testSize];
        var text = new char[testSize];
        var isText = true;

        // Read raw bytes
        var rawLength = fileStream.Read(rawData, 0, rawData.Length);
        fileStream.Seek(0, SeekOrigin.Begin);

        // Detect encoding correctly
        if (rawData[0] == 0xef && rawData[1] == 0xbb && rawData[2] == 0xbf)
        {
            encoding = Encoding.UTF8;
        }
        else if (rawData[0] == 0xfe && rawData[1] == 0xff)
        {
            encoding = Encoding.Unicode;
        }
        else if (rawData[0] == 0 && rawData[1] == 0 && rawData[2] == 0xfe && rawData[3] == 0xff)
        {
            encoding = Encoding.UTF32;
        }
        else if (rawData[0] == 0x2b && rawData[1] == 0x2f && rawData[2] == 0x76)
        {
            encoding = Encoding.UTF7;
        }
        else
        {
            encoding = Encoding.Default;
        }

        // Read text and detect the encoding
        using (var streamReader = new StreamReader(fileStream))
        {
            streamReader.Read(text, 0, text.Length);
        }

        using (var memoryStream = new MemoryStream())
        {
            using (var streamWriter = new StreamWriter(memoryStream, encoding))
            {
                // Write the text to a buffer
                streamWriter.Write(text);
                streamWriter.Flush();

                // Get the buffer from the memory stream for comparision
                var memoryBuffer = memoryStream.GetBuffer();

                // Compare only bytes read
                for (var i = 0; i < rawLength && isText; i++)
                {
                    isText = rawData[i] == memoryBuffer[i];
                }
            }
        }

        return isText;
    }
}
复制代码

 

posted on   空明流光  阅读(2619)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示