使用ExeConfigurationFileMap读写配置文件
使用ExeConfigurationFileMap读写配置文件
using System;
using System.IO;
using System.Configuration;
public class AppConfig
{
public string LastLoginId
{
get { return this.GetItem("LastLoginId"); }
set { this.SetItem("LastLoginId", value); }
}
private Configuration config;
public AppConfig()
{
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = this.CreateConfig();
this.config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
}
private string CreateConfig()
{
try
{
string configFile = AppDomain.CurrentDomain.BaseDirectory + @"app.config";
if (!File.Exists(configFile))
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n</configuration>";
using (StreamWriter sw = new StreamWriter(configFile))
{
sw.Write(xml);
}
}
return configFile;
}
catch (Exception ex)
{
string msg = ex.Message;
throw;
}
}
private string GetItem(string item)
{
if (this.config.AppSettings.Settings[item] == null)
{
return string.Empty;
}
else
{
return this.config.AppSettings.Settings[item].Value;
}
}
private void SetItem(string item, string value)
{
if (this.config.AppSettings.Settings[item] == null)
{
this.config.AppSettings.Settings.Add(item, value);
}
else
{
this.config.AppSettings.Settings[item].Value = value;
}
this.Save();
}
private void Save()
{
try
{
this.config.Save(ConfigurationSaveMode.Modified);
}
catch (Exception ex)
{
string msg = ex.Message;
throw;
}
}
}
using System.IO;
using System.Configuration;
public class AppConfig
{
public string LastLoginId
{
get { return this.GetItem("LastLoginId"); }
set { this.SetItem("LastLoginId", value); }
}
private Configuration config;
public AppConfig()
{
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = this.CreateConfig();
this.config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
}
private string CreateConfig()
{
try
{
string configFile = AppDomain.CurrentDomain.BaseDirectory + @"app.config";
if (!File.Exists(configFile))
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n</configuration>";
using (StreamWriter sw = new StreamWriter(configFile))
{
sw.Write(xml);
}
}
return configFile;
}
catch (Exception ex)
{
string msg = ex.Message;
throw;
}
}
private string GetItem(string item)
{
if (this.config.AppSettings.Settings[item] == null)
{
return string.Empty;
}
else
{
return this.config.AppSettings.Settings[item].Value;
}
}
private void SetItem(string item, string value)
{
if (this.config.AppSettings.Settings[item] == null)
{
this.config.AppSettings.Settings.Add(item, value);
}
else
{
this.config.AppSettings.Settings[item].Value = value;
}
this.Save();
}
private void Save()
{
try
{
this.config.Save(ConfigurationSaveMode.Modified);
}
catch (Exception ex)
{
string msg = ex.Message;
throw;
}
}
}