string _configurationFilePath =
System.IO.Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()),
currentConfigFileName);
private static SiteSettings _currentConfiguration;
#endregion
#region Constructor
private SiteSettings()
{
}
#endregion
public static SiteSettings Instance
{
get
{
if (_currentConfiguration == null)
{
Load();
if (_currentConfiguration == null)
_currentConfiguration = new SiteSettings();
}
return _currentConfiguration;
}
}
private static void Load()
{
if (!File.Exists(_configurationFilePath))
{
throw new Exception("Can't locate config file! Check the config file path.");
_currentConfiguration = new SiteSettings();
}
else
{
XmlSerializer ser = new XmlSerializer(typeof(SiteSettings));
StreamReader reader = new StreamReader(_configurationFilePath);
// XML反序列化.
_currentConfiguration = (SiteSettings)ser.Deserialize(reader);
reader.Close();
}
}
private static void Load(string configFile)//这个方法如果改为公开方案那么可以在运行时来读取合适的配置文件,这样就避免在布署时修改多个功能项.
{
_configurationFilePath = configFile;
Load();
}
public static void Save()
{
XmlSerializer ser = new XmlSerializer(typeof(SiteSettings));
FileStream fileOut;
if (!File.Exists(_configurationFilePath))
{
fileOut = new FileStream(_configurationFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
}
else
{
fileOut = new FileStream(_configurationFilePath, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite);
}
// Serialize the object in XML to the given file stream.
ser.Serialize(fileOut, _currentConfiguration);
// Close the file stream.
fileOut.Close();
}
private static string GetBaseDirectory()
{
return System.AppDomain.CurrentDomain.BaseDirectory;
}
#endregion
}
}
这样我们在站点根目录下面建立一个名为"GBSettings.config"的配置文件就可以对它进行读写操作了.
它里面的内容:
Http://Localhost/
GBWeb/
20
200
default
大家注意到这里面的字段和我们建立的类里面的公开属性是一一对应的, 因此如果需要增加新的可配置项目只要添加相关的公开属性即可,其它的公共代码部分就不用动了, 这个配置文件类使