• 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;
        }
    }
  • 相关阅读:
    Ubuntu Linux Matlab 安装 中文乱码 桌面启动器 Could not find the main class: java/splash.png. 终端terminal 直接运行 matlab
    Ubuntu Linux 官网 u盘安装 u盘系统 图文教程
    从google map google earth获得大图 方法总结
    论文查重网址
    [ZZ] Computer Science Conference Rankings
    Ubuntu linux 信使 iptux Window 飞鸽 ipmsg 飞秋 feiq 文件传输
    Ubuntu Linux Matlab mex
    Ubuntu Dell OptiPlex 990 Intel Gigabit CT Desktop Adapter网卡驱动安装
    C++的File类文件操作
    GIS软件比较
  • 原文地址:https://www.cnblogs.com/nanfei/p/14151118.html
Copyright © 2020-2023  润新知