自定义 ConfigHelper.cs 类:
public class ConfigHelper
{
string _configfile;
private string ConfigFile
{
get
{
if (String.IsNullOrEmpty(_configfile))
{
string assemblyFile = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
_configfile = assemblyFile + ".config";
}
return _configfile;
}
}
public ConfigHelper(string configFile)
{
_configfile = configFile;
}
/// <summary>
/// 获取配置文件的属性
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetAppSettingsValue(string key)
{
string value = string.Empty;
try
{
//if (File.Exists(ConfigFile))
{
XmlDocument xml = new XmlDocument();
xml.Load(ConfigFile);
XmlNode xNode = xml.SelectSingleNode("//appSettings");
XmlElement element = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
value = element.GetAttribute("value").ToString();
}
}
catch { }
return value;
}
/// <summary>
/// 获取配置文件的属性
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetConnectionStringValue(string key)
{
string value = string.Empty;
try
{
//if (File.Exists(ConfigFile))
{
XmlDocument xml = new XmlDocument();
xml.Load(ConfigFile);
XmlNode xNode = xml.SelectSingleNode("//connectionStrings");
XmlElement element = (XmlElement)xNode.SelectSingleNode("//add[@name='" + key + "']");
value = element.GetAttribute("connectionString").ToString();
}
}
catch { }
return value;
}
}
GZProxyServer.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ServiceName" value="GZProxyServer"/>
<add key="DisplayName" value="GZProxyServer在线代理服务"/>
<add key="Description" value="支持HTTP代理"/>
<add key="ListeningIPInterface" value="127.0.0.1"/>
<add key="ListeningPort" value="8889"/>
<add key="CertificateFile" value="cert.cer"/>
</appSettings>
</configuration>
传入指定的config配置文件路径,取该文件的配置信息
ConfigHelper configHelper = new ConfigHelper("D:\project\_garson\GZServiceTools\Debug\GZProxyServer.exe.config");
string ServiceName = configHelper.GetAppSettingsValue("ServiceName");
string DisplayName = configHelper.GetAppSettingsValue("DisplayName");
string Description = configHelper.GetAppSettingsValue("Description");
单独DLL中的app.config
string configFile = System.IO.Path.Combin(AppDomain.CurrentDomain.BaseDirectory, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name+".dll.config");
ConfigHelper configHelper = new ConfigHelper(configFile);
string ServiceName = configHelper.GetAppSettingsValue("ServiceName");
string DisplayName = configHelper.GetAppSettingsValue("DisplayName");
string Description = configHelper.GetAppSettingsValue("Description");