简体   繁体   中英

Can not read Config File

I have a config file in my project, which I am not able to read in for some reason. Similar code has worked for me in the past. I am not sure what am I doing wrong here. I was wondering if someone would be able to have a look and let me know if I am doing something wrong. Please help...

Here's my code:

  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;

Here's my Config File:

<?xml version="1.0"?/>
<configuration>
  <add key="logFilePath" value=".//Results//" />
  <add key="logFileName" value="Output.xml" />
</configuration>

Thanks in advance, Harit

harit, try amending your structure to:

<?xml version="1.0"?/>
<configuration>
   <appSettings>
     <add key="logFilePath" value=".//Results//" />
     <add key="logFileName" value="Output.xml" />
   <appSettings>
</configuration>

Using the ConfigurationManager creates the requirement for this exact structure to be present. it should work as planned with the above change.

The AppSettings Collection is missing from your configuration. You only have the root-level of configured. But you are requesting in your code.

Your configuration should be

<configuration>
   <appSettings>
      <add key="logFilePath" value=".//Results//" />
      <add key="logFileName" value="Output.xml" />
   </appSettings>
</configuration>

Read values from different 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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM