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> ");
str.Append("///" + node.Attributes["message"].Value);
str.Append(" /// </summary> ");
str.Append("R"+node.Attributes["code"].Value);
str.Append("=");
str.Append(eNum.ToString());
str.Append(", ");
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(" } } }");
sw.Flush();
sw.Close();
sr.Close();

原文地址:https://www.cnblogs.com/wdw31210/p/3673754.html