我在很多层面上都犯了罪。我希望有人能告诉我一个更好的方法来重写这个 c#。
我的任务是在运行时修改 web.config 的一部分,以删除 elmah 错误电子邮件的一部分主题并插入框名称。
原因是我们不能相信我们的厘米人员能够始终如一地做到这些,因此我们浪费时间在错误的盒子上调试错误。
因此,面对眼前的丑陋,我开始写作……
这是我要修改的 web.config 中的部分
<elmah>
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/ELMAH" />
<errorMail from="..." to="..."
subject="Application: EditStaff_MVC, Environment:Dev, ServerBoxName: AUST-DDEVMX90FF"
async="true" />
</elmah>
这是代码。
private void UpdateElmahErrorEmailSubject( string appPath )
{
string machineName = System.Environment.MachineName;
//System.Collections.IDictionary config = ( System.Collections.IDictionary ) ConfigurationManager.GetSection( "elmah" ); ;
//System.Configuration.Configuration config2 = ( System.Configuration.Configuration ) ConfigurationManager.GetSection( "elmah/errorMail" );
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( appPath );
if ( config == null )
{
return;
}
ConfigurationSectionGroup sectionGroup = config.GetSectionGroup( "elmah" );
ConfigurationSection section = config.GetSection( "elmah/errorMail" );
// i was not able to get directly to the subject, so I had to write it as xml
string s = section.SectionInformation.GetRawXml();
string search = "ServerBoxName:";
//here is where i started to feel dirty, direct string parsing.
int startIndex = s.IndexOf( search );
int endIndex = s.IndexOf( "\"", startIndex );
string toReplace = s.Substring( startIndex, ( endIndex - startIndex ) );
s = s.Replace( toReplace, search + " " + machineName );
section.SectionInformation.SetRawXml( s );
config.Save();
}
任何人都可以绕过字符串解析。我尝试将它作为 xml 获取,但仍然以字符串解析主题结束。有没有更好的办法?
谢谢,
埃里克-