应用程序关闭后,App.config 将返回到其默认状态

本文关键字:返回 默认 状态 config App 应用程序 | 更新日期: 2023-09-27 17:56:18

这是配置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
   <sectionGroup name="CardValidator"
              type="Micro.CardValidator.Models.CardValidatorSectionGroup, Micro.CardValidator">
  <section name="Settings" type="Micro.CardValidator.Models.Settings, Micro.CardValidator" />
</sectionGroup>

 public class CardValidatorSectionGroup : ConfigurationSectionGroup {
    [ConfigurationProperty("Settings", IsRequired = false)]
    public Settings Settings {
        get { return (Settings) Sections["Settings"]; }
    }
}
public class Settings : ConfigurationSection {
    [ConfigurationProperty("LastSoftwareVersionInstalled", IsRequired = true)]
    public string LastSoftwareVersionInstalled {
        get { return (string) base["LastSoftwareVersionInstalled"]; }
        set { base["LastSoftwareVersionInstalled"] = value; }
    }
    [ConfigurationProperty("InstallationPlaceCode", IsRequired = true)]
    public int InstallationPlaceCode {
        get { return (int)base["InstallationPlaceCode"]; }
        set { base["InstallationPlaceCode"] = value; }
    }
    [ConfigurationProperty("InstallationPlaceName", IsRequired = true)]
    public string InstallationPlaceName {
        get { return (string)base["InstallationPlaceName"]; }
        set { base["InstallationPlaceName"] = value; }
    }
}
 public class Config {
    private Settings Settings { get; set; }
    public Station InstallationPlace {
        get {
            return new Station(Settings.InstallationPlaceCode, Settings.InstallationPlaceName);
        }
        set {
            Settings.InstallationPlaceCode = value.Id;
            Settings.InstallationPlaceName = value.ShortName;                
        }
    }
    public string LastInstalledSoftwareVersion {
        get { return Settings.LastSoftwareVersionInstalled; }
        set { Settings.LastSoftwareVersionInstalled = value; }
    }
    private readonly Configuration cfg;
    public Config() {
        cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        CardValidatorSectionGroup akmSectionGroup = (CardValidatorSectionGroup) cfg.SectionGroups["CardValidator"];
        Debug.Assert(akmSectionGroup != null, "AkmSectionGroup can not be null");
        Settings = akmSectionGroup.Settings;
    }
    public void Save(ConfigurationSaveMode saveMode = ConfigurationSaveMode.Full) {
        cfg.Save(saveMode);
    }
}

我看到保存后,数据出现在配置文件中。但是当应用程序关闭时,配置文件返回到其空状态。

应用程序关闭后,App.config 将返回到其默认状态

exe目录中的app.config是只读的。您必须使用用户特定的位置:

cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);