【常用代码】批量替换Code

本文介绍了通过正则表达式替换代码中特定模式,并利用文件读写操作优化代码流程的技术。详细阐述了如何加载文件内容到内存,进行模式匹配替换,并将修改后的代码写回文件。适用于希望提高代码效率和维护性的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private static readonly string _filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CodeFolder");

        private static Dictionary<string, string> _codes = new Dictionary<string, string>();

        //call repository codes changed
        private static readonly Regex _oldTextRegex = new Regex(@"XXX\.XX\(repositoryIP, repositoryPort, XXX\.\w+\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly Regex _saveText = new Regex(@"XXX\.\w+", RegexOptions.Compiled);
        private const string NEW_TEXT = "MethodName({0}, dataFilePathDic[{0}])";

        static void Main(string[] args)
        {
            LoadFile();

            ReplaceCodes();
            Console.WriteLine("Please type anykey to exist");
            Console.ReadKey();
        }

        private static void ReplaceCodes()
        {
            foreach (var codes in _codes)
            {
                string newCodes = _oldTextRegex.Replace(codes.Value, ReplaceDetail);
                WriteFile(codes.Key, newCodes);
                Console.WriteLine("Replace " + codes.Key + " code completed");
            }
        }

        private static string ReplaceDetail(Match match)
        {
            var saveCodeMatch = _saveText.Match(match.Value);
            if (saveCodeMatch.Success)
            {
                return string.Format(NEW_TEXT, saveCodeMatch.Value);
            }

            return "[not found]";
        }

        private static void LoadFile()
        {
            if (!Directory.Exists(_filePath))
            {
                Directory.CreateDirectory(_filePath);
                return;
            }

            DirectoryInfo fileDirectory = new DirectoryInfo(_filePath);
            var files = fileDirectory.GetFiles("*.cs");
            foreach (var file in files)
            {
                var fs = file.OpenRead();
                StreamReader sr = new StreamReader(fs);
                _codes[file.FullName] = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                fs.Close();
                fs.Dispose();
            }
        }

        public static void WriteFile(string filePath, string content)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Create))
            {
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(content);
                writer.Close();
            }
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值