zoukankan      html  css  js  c++  java
  • C# 批量替换文本文件里的内容

    void Main()
    {
        var result = replaceFiles(@"C:UsersadminDesktopopencv31opencvmybuild", "*.*", @"C:UsersadminDesktopopencv31opencvmybuild", '\'
            , new string[] { @"C:UsersadminDesktopopencv31opencvmybuild.vs" });
        result.Dump();
        result = replaceFiles(@"C:UsersadminDesktopopencv31opencvmybuild", "*.*", @"C:UsersadminDesktopopencv31opencvmybuild", '/'
            , new string[] { @"C:UsersadminDesktopopencv31opencvmybuild.vs" });
        result.Dump();
        result = replaceFiles(@"C:UsersadminDesktopopencv31opencvmybuild", "*.*", @"C:UsersadminDesktopopencv31opencv", '\'
            , new string[] { @"C:UsersadminDesktopopencv31opencvmybuild.vs" });
        result.Dump();
        result = replaceFiles(@"C:UsersadminDesktopopencv31opencvmybuild", "*.*", @"C:UsersadminDesktopopencv31opencv", '/'
            , new string[] { @"C:UsersadminDesktopopencv31opencvmybuild.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;
        }
    }
  • 相关阅读:
    外部排序
    oceanbase tpcc 关键总结
    TPCC测试
    最简单的oracle 19c安装教程
    unix进程环境
    tars以docker方式安装
    异常安全的赋值运算符函数
    linux 定时器setitimer使用
    libevent学习-reactor设计模式及代码示例
    linux中可执行程序搜索动态链接库的顺序
  • 原文地址:https://www.cnblogs.com/nanfei/p/14151118.html
Copyright © 2011-2022 走看看