![](/img/trans.png)
[英]How to Update (Add/Modify/Delete) keys in AppSettings section of web.config at runtime
[英]How to modify web.config section runtime?
我創建了一個直接映射到Web的ConfigSection
的類。 配置。 我的課程定義如下:
public class myConfiguration: ConfigurationSection
{
public myConfiguration()
{
//
// TODO: Add constructor logic here
//
}
[ConfigurationProperty("fileName", IsRequired = true)]
public string FileName
{
get { return this["fileName"] as string; }
}
[ConfigurationProperty("rootNode", IsRequired = true)]
public string RootNode
{
get { return this["rootNode"] as string; }
}
[ConfigurationProperty("childNode", IsRequired = true)]
public string ChildNode
{
get { return this["childNode"] as string; }
}
[ConfigurationProperty("comparableAttributes", IsRequired = true)]
public string ComparableAttributes
{
get
{ return this["comparableAttributes"] as string; }
}
}
我在web.config文件中創建了如下部分:
<configSections>
<section name="myConfigDemo" type="myConfiguration"/>
</configSections>
然后我用這個部分作為
<myConfigDemo fileName="myXml.xml" rootNode="world" childNode="country" comparableAttributes="id, population">
</myConfigDemo>
現在的問題是如何在運行時分配fileName = "anotherFile.xml"
? 我試過了
[ConfigurationProperty("fileName", IsRequired = true)]
public string FileName
{
get { return this["fileName"] as string; }
set {
string str = this["fileName"] as string;
str = value; }
}
但我的Visual Studio使我的電腦掛起我使用上面的代碼! 我知道該屬性是只讀,當你只使用get
但set
讓我的電腦掛! 我該怎么做才能更改文件名運行時?
有.net類設計用於更准確地訪問幾乎所有可以在.config文件中找到的內容(而不僅僅是appSettings或ConnectionStrings元素); 文檔: http : //msdn.microsoft.com/en-us/library/x1et32w6.aspx
我不確定他們是否提供改變價值觀的方法(看看)。 但是,一個gotcha:config文件旨在在啟動時配置應用程序; 換句話說,應用程序在啟動時讀取文件,然后再次手動或通過進程更改文件。 使用asp.net應用程序,這意味着應用程序將自動重啟(默認情況下; IIS設置)。
如果您確實想在運行時重新配置應用程序,則每次保存文件時都會強制它重新啟動。 因此,在這種情況下,編寫代碼以在內存中進行所有更改(例如,通過使用xml類),然后立即保存所有內容。
app-pool中有一個設置可以禁用配置更改時的自動重啟; 但是,如果這樣做,當您進行配置更改時,應用程序將不會重新啟動,並且您必須編寫代碼才能重新啟動它以獲取這些更改。
如果要將自定義配置類自動序列化為xml元素,則此類可能是您的朋友: http : //msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
我希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.