0
我試圖創建一個自定義設置類來存儲一些用戶範圍的設置。我在幾個月前完成了這個工作,工作得很好,但我不記得所有的細節,也無法再訪問源代碼。這是我到目前爲止有:試圖創建一個自定義的部分設置文件
CustomSettings.cs
internal sealed partial class CustomSettings : global::System.Configuration.ApplicationSettingsBase
{
private static CustomSettings defaultInstance = ((CustomSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new CustomSettings())));
public static CustomSettings Default
{
get
{
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
public global::System.Collections.Generic.List<global::LearningProject.Types.Product> Products
{
get
{
return ((global::System.Collections.Generic.List<global::LearningProject.Types.Product>)(this["Products"]));
}
set
{
this["Products"] = value;
}
}
}
Product.cs
[Serializable]
public class Product
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Id")]
public int Id { get; set; }
}
這裏的的App.config文件,幷包含一個樣本Product
:
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LearningProject.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
<section name="LearningProject.CustomSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
<userSettings>
<LearningProject.CustomSettings>
<setting name="Products" serializeAs="Xml">
<ArrayOfProduct>
<Product>
<Name>Product1</Name>
<Id>ProductID</Id>
</Product>
</ArrayOfProduct>
</setting>
</LearningProject.CustomSettings>
</userSettings>
</configuration>
現在,我得到null
當我嘗試獲得Products
列表:
List<Product> products = CustomSettings.Default.Products;
這意味着無論是我做錯了什麼(XML屬性,也許?)還是我缺少的一個步驟。另外請注意,Settings1.settings
(由VS生成)已經存在,並且我的CustomSettings
類只是將方法添加到默認的自動生成的設置文件。我只是想知道是否有人曾經這樣做過。任何幫助表示讚賞。
我還是得到null當我手動將它們添加到'app.config'時,但通過代碼添加它似乎工作,但即使如此,我仍然無法在'app.config'中看到它們,這表明它們正在保存在其他地方。任何想法? – PoweredByOrange 2013-06-26 16:23:05
更正了我的答案:忘記了位於%appdatalocal%\ project_name .. \ user.config中的0123.tag.Local配置。完成後將其刪除,否則將從中取出設置 – cdmnk 2013-06-27 10:18:14
但是,如何將設置直接放在app.config中?當我在幾個月前第一次完成時,所有設置都是在app.config中寫入/讀取的。 – PoweredByOrange 2013-06-27 16:04:20