C# 会自动替换 变量 把形如 "{{varName}}" 替换成对应的数值
C# 会自动替换 变量 把形如 "{{varName}}" 替换成对应的数值
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Common { public class DynamicVariableHelper { /// <summary> /// 会自动替换 变量 把形如 "{{varName}}" 替换成对应的数值 /// </summary> public static void ReplaceFileVar(string srcFile, string targetFile) { /* * 设置webconfig连接字符串 */ string webconfigpath = Path.Combine("./", srcFile); //修改第一个数据库连接 string webcofnigstring2 = File.ReadAllText(webconfigpath); webcofnigstring2 = ReplaceStringVar(webcofnigstring2); //循环替换所有的 {{DBSERVER}} 这种变量 效率比较低,改成上面的replace //foreach (Match item in mat) //{ // Console.WriteLine(item.Groups[1]); // var name = item.Groups[1].Value; // if (! string.IsNullOrEmpty( InstallContext.Get(name))) // { // webcofnigstring2.Replace(@"{{"+ name + "}}", InstallContext.Get(name)); // } //} File.WriteAllText(targetFile, webcofnigstring2); } /// <summary> /// 会自动替换 变量 把形如 "{{varName}}" 替换成对应的数值 /// </summary> public static string ReplaceStringVar(string str) { Regex reg = new Regex(@"\{\{(.*?)\}\}"); //var mat = reg.Matches(webcofnigstring2); str = reg.Replace(str, new MatchEvaluator(m => InstallContext.Get(m.Groups[1].Value) == string.Empty ? m.Value : InstallContext.Get(m.Groups[1].Value) )); return str; } } public static class InstallContext { private static Dictionary<string, string> kvs = new Dictionary<string, string>(); public static string Get(string index) { if (kvs.ContainsKey(index)) { return kvs[index]; } else { return string.Empty; } } public static void Set(string index, string value) { kvs[index] = value; } //private static InstallContext instance = new InstallContext(); //private InstallContext() //{ //} //public static InstallContext GetInstance() //{ // return instance; //} } }