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 2020-12-17 18:13  空明流光  阅读(2611)  评论(0编辑  收藏  举报

导航