我玩弄.NET的配置支持(ConfigurationManager类和相关的支持类)。我想写一个应用程序,一旦安装:我是否必须从ConfigurationSection派生来支持每个用户的设置?
- 在foo.exe.config(在程序文件中)具有默认设置。
- 用户以后可能会覆盖应该保留的非默认值的设置。
- 用户的首选项应该保留在用户的配置文件中,因为他不应该具有对Program Files目录的写入权限。
应用程序在设置时应使用用户的首选项,否则使用默认值。
看起来这应该很容易 - 这是一个非常普遍的模式。但我在这方面的尝试遇到了颠簸,我想知道我是否采取了正确的方法。
以下代码会产生运行时异常“ConfigurationSection属性在锁定时无法编辑”。
using System;
using System.Configuration;
namespace DemoAppSettingsProblem
{
class Program
{
static void Main(string[] args)
{
Configuration userConfig =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
if (userConfig.AppSettings.Settings["foo"] != null)
userConfig.AppSettings.Settings.Remove("foo");
userConfig.AppSettings.Settings.Add("foo", "The string is foo.");
userConfig.Save(ConfigurationSaveMode.Modified); // exception!
}
}
}
的问题是,.NET定义<appSettings>
部分都被定义为默认allowExeDefinition=MachineToApplication
(见本nice post微软的伊雷娜·肯尼迪)。这将禁止将该部分写入用户的配置文件(本地或漫游)。
所以,我想我需要定义我自己的部分,与allowExeDefinition=MachineToLocalUser
。但据我可以从MSDN文档中知道,这意味着我需要创建自己的配置类,从ConfigurationSection
派生。那里的例子指出我的工作比我期待的要多,这通常会引发我警钟的问题,以致我做错了事。
实现这个真的很难吗?有没有一种简单的方法来提供支持,或者我应该采用不同的方法?
什么版本的.NET,你定位? – 2009-05-06 19:52:33