您的位置:首页 > 移动开发

Visual Studio某些项目类型不能使用ConfigurationManager读取app.config文件的解决办法

2016-11-18 17:36 741 查看
在做C#开发的时候经常使用app.config或者web.config,将一些简单的配置信息存在config文件里面,然后使用ConfigurationManager来读取很方便,但是最近在开发load test的时候发现这个方法不灵了,检查引用发现System.configuration还在,config文件也没有问题。

最后Google了一下才发现,原来是项目类型的问题,简单来说就是Load Test类型的文件或者"Web Performance and Load Test Project"类型的项目不支持读取config文件。

下面直接上代码:

/// <summary>
/// 从app.config取得一个key。
/// </summary>
/// <param name="key">参数名。</param>
/// <returns>参数值。</returns>
public static string GetAppSetting(string key)
{
if (ConfigurationManager.AppSettings[key] != null)
{
return ConfigurationManager.AppSettings[key];
}
else
{
throw new AdventException("Unknown setting: " + key);
}
}

/// <summary>
/// Get configuration for web and load test project.
/// </summary>
/// <returns>The configuration.</returns>
private static Configuration GetConfiguration()
{
string configFileName = string.Empty;

try
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
var path = "App.config的路径";
configFileMap.ExeConfigFilename = path;
Configuration configObj = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

return configObj;
}
catch (Exception ex)
{
throw ex;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐