我有更改 web.config 中值的功能 但我的问题是它没有正确获取 web.config 的路径并抛出
“找不到文件‘C:\Users\maxnet25\Web.config’” 它在 xmlDoc.Load() 函数上出错。
我的代码:
public void UpdateConfigKey(string strKey, string newValue)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config");
if (!ConfigKeyExists(strKey))
{
throw new ArgumentNullException("Key", "<" + strKey + "> not find in the configuration.");
}
XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings");
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
childNode.Attributes["value"].Value = newValue;
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Label1 .Text ="Key Upated Successfullly";
}
请您参考如下方法:
给出了什么错误消息?
无论哪种方式,您都不会真正以正确的方式修改 web.config。你应该看看 System.Configuration.ConfigurationManager类,因为它以结构化方式提供对 web.config 文件的编程访问。请注意,要访问此类,您需要将对 System.Configuration.dll 的引用添加到您的项目中,以将 ConfigurationManager 纳入范围。
如果您查看 GetSection method 的示例代码,它展示了如何在 .net 配置文件的 appSettings 部分中创建/添加设置,因此该示例应该足以让你到达你想去的地方。
如果您确实想使用这种方法来操作您的 web.config 文件,我怀疑:
AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config")
不正确,根据您在错误消息中显示的路径。尝试删除 ..\..\并查看是否有效。 AppDomain.CurrentDomain.BaseDirectory应该指向您的 web.config 文件的位置,无需修改。
