c# 运行时替换某文件源代码(将XML 转换成 某个枚举并写入源文件)

时间:2023-03-09 23:00:43
c# 运行时替换某文件源代码(将XML 转换成 某个枚举并写入源文件)

var sr = new StreamReader(Server.MapPath("~/WEB-INF/rule.config"));

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WEB-INF/rule.config"));

XmlNodeList nodeList = doc.SelectNodes("root/rule/add");

var str = new StringBuilder();
int eNum = 0;
if (nodeList != null)
foreach (XmlNode node in nodeList)
{
if (node.Attributes["message"] == null || node.Attributes["code"] == null) continue;
str.Append("/// <summary>\r");
str.Append("///" + node.Attributes["message"].Value);
str.Append("\r/// </summary>\r");
str.Append("R"+node.Attributes["code"].Value);
str.Append("=");
str.Append(eNum.ToString());
str.Append(",\r");
eNum++;
}
//去掉尾巴逗号
if (str.Length > 1)
str.Length = str.Length - 2;

var sw = new StreamWriter(Server.MapPath("~/WEB-INF/Class1.cs"));

sw.Write(str.ToString());
sw.Write("\r}\r}\r}");
sw.Flush();
sw.Close();
sr.Close();