.NET 2.0中是否存在用于的任何受支持的API,将写入主exe的.config文件 userSettings 部分?

该方案是:

Winforms 2.0应用程序。

我有一个设置(具有数据库连接字符串,如果您需要知道的话),它具有用户级别的作用域。这意味着当用户保存设置的值时,每个用户都有一个由.net创建的user.config文件。

对于首次运行该应用程序的新用户,该应用程序的主exe的.config文件在“用户设置”部分中包含默认值。在项目属性的“设置”选项卡中创 build 置时,此部分由Visual Studio创建。

现在,我希望允许计算机中的任何管理员用户都可以更改新用户的默认值。只有管​​理员才具有此选项,因为普通用户始终无权写入主exe的.config文件。

我发现了如何将用户设置写入用户的.config文件,以及如何写入主.config文件的appSettings部分。但是当尝试找出如何写入主.config的userSettings部分时,我的谷歌搜索失败了

我唯一的机会失败回到System.Xml并在XmlDocument中手动加载.config吗?

最佳答案

经过研究,我想出了这个解决方案。这是一个较低的级别,但是仍然可以通过.NET配置API进行操作,而不必手动解析.config文件。

static void SaveUserSettingDefault(string clientSectionName, string settingName, object settingValue)
{
    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // find section group
    ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];
    if (group == null) return;

    // find client section
    ClientSettingsSection clientSection = group.Sections[clientSectionName] as ClientSettingsSection;
    if (clientSection == null) return;

    // find setting element
    SettingElement settingElement = null;
    foreach (SettingElement s in clientSection.Settings)
    {
        if (s.Name == settingName)
        {
            settingElement = s;
            break;
        }
    }
    if (settingElement == null) return;

    // remove the current value
    clientSection.Settings.Remove(settingElement);

    // change the value
    settingElement.Value.ValueXml.InnerText = settingValue.ToString();

    // add the setting
    clientSection.Settings.Add(settingElement);

    // save changes
    config.Save(ConfigurationSaveMode.Full);
}

给定具有以下内容的.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="MyAssembly.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <MyAssembly.Properties.Settings>
            <setting name="SqlConnectionString" serializeAs="String">
                <value>Server=(local);Database=myDatabase;Integrated Security=true;</value>
            </setting>
        </MyAssembly.Properties.Settings>
    </userSettings>
</configuration>

您可以这样使用它:
if (RunningAsAdmin) // save value in main exe's config file
{
    SaveUserSettingDefault(@"MyAssembly.Properties.Settings", @"SQLConnectionString", theNewConnectionString);
}
else // save setting in user's config file
{
    Settings.Default. SQLConnectionString = theNewConnectionString;
    Settings.Default.Save();
}

10-07 19:40
查看更多