Как записать в раздел .config userSettings основного exe?

Это просто означает, что у вас не установлен пакет, вам нужно сначала установить пакет. В зависимости от вашей ОС, команды различаются.

6
задан Sergio Acosta 10 March 2009 в 20:36
поделиться

2 ответа

После некоторого исследования я предложил это решение. Это - немного низкий уровень, но все еще проходит конфигурацию.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
ответ дан 9 December 2019 в 22:40
поделиться

Я думаю да - вручную пишущий в .config файл, единственный путь. Или можно позволить администратору отредактировать .config-файл самому.

1
ответ дан 9 December 2019 в 22:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: