gpt4 book ai didi

c# - 我是否必须派生自 ConfigurationSection 以支持每个用户的设置?

转载 作者:行者123 更新时间:2023-11-30 16:36:25 28 4
gpt4 key购买 nike

我正在研究 .NET 的配置支持(ConfigurationManager 类和相关的支持类)。我想编写一个应用程序,一旦安装:

  • 在 foo.exe.config 中有默认设置(在 Program Files 中)。
  • 用户以后可以使用非默认值覆盖设置,这些设置应该保留。
  • 用户的首选项应该保留在用户的配置文件中,因为他不应该对 Program Files 目录具有写入权限。

应用程序应在设置时使用用户的首选项,否则使用默认值。

看起来这应该很容易 - 这是一种非常常见的模式。但我在这方面的尝试遇到了障碍,我想知道我是否采取了正确的方法。

以下代码产生运行时异常“ConfigurationSection properties cannot be edited when locked”。

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 (参见 Microsoft 的 Irena Kennedy 的 nice post)。这禁止将部分写入用户的配置文件(本地或漫游)。

因此,我假设我需要定义自己的部分,使用 allowExeDefinition=MachineToLocalUser .但据我从 MSDN 文档中得知,这意味着我需要创建自己的配置类,派生自 ConfigurationSection .那里的例子让我完成了比预期更多的工作,这通常会敲响我做错事的警钟。

实现这个目标真的有那么难吗? .NET 是否提供了一种简单的方法来支持这一点,或者我是否应该完全采用不同的方法?

最佳答案

我已经使用了设置功能,它会为您将用户设置写入应用配置...

http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx

关于c# - 我是否必须派生自 ConfigurationSection 以支持每个用户的设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831281/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com