我的项目中有一个配置文件,由于某种原因我无法读取。类似的代码过去对我有用。我不确定我在这里做错了什么。我想知道是否有人能够看看,如果我做错了,请告诉我。请帮忙......
这是我的代码:
KeyValueConfigurationCollection settings;
Configuration config;
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = "myProject.exe.config";
config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
settings = config.AppSettings.Settings;
this.logFilePath = settings["logFilePath"].Value;
this.logFilePath = settings["logFileName"].Value;
这是我的配置文件:
<?xml version="1.0"?/>
<configuration>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</configuration>
提前致谢, Harit
答案 0 :(得分:2)
harit,尝试修改你的结构:
<?xml version="1.0"?/>
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
<appSettings>
</configuration>
使用ConfigurationManager
创建了对此精确结构的要求。它应该按照上述变化按计划运作。
答案 1 :(得分:0)
您的配置中缺少AppSettings Collection。您只有配置的根级别。但是你要在你的代码中提出要求。
您的配置应该是
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</appSettings>
</configuration>
答案 2 :(得分:0)
从不同的web.config中读取值:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + @"second.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
ConfigurationSection mySection = config.GetSection("countoffiles");
if (config.AppSettings.Settings.Count > 0)
{
System.Configuration.KeyValueConfigurationElement customSetting =
config.AppSettings.Settings["countoffiles"];
if (customSetting != null)
{
Response.Write(customSetting.Value);
}
else
{
Console.WriteLine("No countoffiles application string");
}
}