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

时间:2014-04-03 11:25:27

标签: c# config configsection

这是配置:

<?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);
    }
}

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

1 个答案:

答案 0 :(得分:0)

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

cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);