系统默认的App.config文件,是XML格式的,可通过以下方式进行读取
class SystemConfig:ConfigurationSection
{
[ConfigurationProperty("id")]
public int Id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[ConfigurationProperty ("aaServerName")]
public string ServerName
{
get
{
return (string)this["aaServerName"];
}
set
{
this["aaServerName"] = value;
}
}
[ConfigurationProperty ("DBName")]
public string DBName
{
get
{
return (string)this["DBName"];
}
set
{
this["DBName"] = value;
}
}
[ConfigurationProperty("Config1")]
public string UserPwd
{
get
{
return (string)this["Config1"];
}
set
{
this["Config1"] = value;
}
}
[ConfigurationProperty ("Config2")]
public string StationNo
{
get
{
return (string)this["Config2"];
}
set
{
this["Config2"] = value;
}
}
[ConfigurationProperty("Config3")]
public string UserName
{
get
{
return (string)this["Config3"];
}
set
{
this["Config3"] = value;
}
}
}
public class SystemConfigOp//:ConfigurationSection
{
private static bool m_SingleFlag=false ;
private static Configuration m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
private static SystemConfigOp m_SelfObject = null;
private bool m_HaveSection = false;
private SystemConfig m_SysCon;
public SystemConfigOp()
{
if (m_SingleFlag )
{
ScSettleError.CreateNewError(this, "100", "不能重复创建系统配置对象");
}
m_SingleFlag = true;
m_SelfObject = this;
m_SysCon = new SystemConfig();
}
private void CloneSysConfigToMe(SystemConfig p_Source)
{
this.ServerName = p_Source.ServerName;
this.DBName = p_Source.DBName;
this.StationNo = p_Source.StationNo;
this.UserName = p_Source.UserName;
this.UserPwd = p_Source.UserPwd;
}
public void SaveConfig()
{
if (!m_HaveSection)
{
m_config.Sections.Add("SystemInfo", m_SysCon );
}
m_config.Save(ConfigurationSaveMode.Minimal);
}
public void ReadConfig()
{
ConfigurationSection configTmp = m_config.Sections["SystemInfo"];
if (configTmp != null)
{
if (configTmp is SystemConfig)
{
SystemConfig sysConfig = configTmp as SystemConfig;
CloneSysConfigToMe(sysConfig);
m_HaveSection = true;
return;
}
}
m_HaveSection = false;
}
public int Id
{
get
{
return m_SysCon.Id;
}
set
{
m_SysCon.Id = value;
}
}
public string ServerName
{
get
{
return m_SysCon.ServerName;
}
set
{
m_SysCon.ServerName = value;
}
}
public string DBName
{
get
{
return m_SysCon.DBName ;
}
set
{
m_SysCon.DBName = value;
}
}
public string UserPwd
{
get
{
return m_SysCon.UserPwd ;
}
set
{
m_SysCon.UserPwd = value;
}
}
public string StationNo
{
get
{
return m_SysCon .StationNo ;
}
set
{
m_SysCon.StationNo = value;
}
}
public string UserName
{
get
{
return m_SysCon.UserName ;
}
set
{
m_SysCon.UserName = value;
}
}
}
这里要注意的时如果将来个类合并到一起,则不能在构造函数中限制唯一模式(Singleton),因为好像Configuration 对象在SAVE时多次创建了该对象。