2

I am trying to read value from appSettings but getting null value in return. Also getting null value in element variable present in my class file. Below is my class file content.

using System;
using System.Configuration;

namespace SampleDLL
{
    public class Class1
    {
        private static string GetAppSetting(Configuration config, string key)
        {
            var testValue = ConfigurationManager.AppSettings[key]; //Alternate option.
            var element = config.AppSettings.Settings[key];
            if (element == null) return string.Empty;
            var value = element.Value;
            return !string.IsNullOrEmpty(value) ? value : string.Empty;
        }

        public void GetDataAppConfig()
        {
            Configuration config = null;
            var exeConfigPath = GetType().Assembly.Location;
            try
            {
                config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
            }
            catch (Exception exception)
            {
                //handling exception here.
            }
            if (config != null)
            {
                var myValue = GetAppSetting(config, "myKey");
            }
        }
    }
}

My app.config file is as below

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="myKey" value="TestValue"/>
  </appSettings>
</configuration>

Reference to System.Configuration is present in my Class Library Project. I am calling GetDataAppConfig form from the one windows form present in another project of same solution.

Edited

I am using config file present in my Class Library Project.

enter image description here

My WinForm class is as below which I am using to call GetDataAppConfig present in classClass1 of class library project.

using System;
using System.Windows.Forms;
using SampleDLL;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var class1 = new Class1();
            class1.GetDataAppConfig();
        }
    }
}
Manoj Naik
  • 386
  • 4
  • 18
  • Try use `AppSettingsSection` instead of a `NameValueCollection`. Like `config.GetSection("appSettings").Settings[key].Value;` – M. Wiśnicki Dec 05 '16 at 08:57
  • Possible duplicate of [Read from App.config in a Class Library project](http://stackoverflow.com/questions/9871948/read-from-app-config-in-a-class-library-project) – Liam Dec 05 '16 at 10:36
  • @Liam I do not want to use config file present in client application. – Manoj Naik Dec 05 '16 at 11:00
  • Of course even if you do get this working, any config added to the clients application would override your own. Basically, don't do this, your just giving yourself a headache you could do without. – Liam Dec 05 '16 at 11:04
  • Also, possible duplicate of [Can a class library have an App.config file?](http://stackoverflow.com/questions/4817051/can-a-class-library-have-an-app-config-file) – Liam Dec 05 '16 at 11:06

1 Answers1

2

The problem is that you're calling OpenExeConfiguration() with the wrong configuration file, by determining the configuration file using

var exeConfigPath = GetType().Assembly.Location;

You're actually using the path of the Class Library that defines your Class1 type when you actually want to load the configuration of the current client referencing Client1 (the WinForm app in your case).

Try this instead:

config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

See MSDN


Update:

Since you want to embed the configuration file in your Class Library project, you'll have to follow the following steps:

  • Change the file name from App.Config to something else (so that it won't collide with the client's configuration file).

  • Change the Build Action of the file to Content

  • Change Copy to output directory to Copy always

Then in your code:

try
{
    var configurationMap = new ExeConfigurationFileMap
    {
        // assuming name of your file is "ClassiLibrary1.config"
        ExeConfigFilename = Path.Combine(exeConfigPath, "ClassLibrary1.config")
    };

    config = ConfigurationManager.OpenMappedExeConfiguration(configurationMap, ConfigurationUserLevel.None);
}
haim770
  • 48,394
  • 7
  • 105
  • 133
  • FYI, my config file is present in my class library project. I missed to mention the same. I have edited my question for this. – Manoj Naik Dec 05 '16 at 10:22
  • @ManojNaik Add the config to the calling application, not the class library. The class library is consumed by the calling application, this is the context, so the config should also be in the context of the consuming application – Liam Dec 05 '16 at 10:35
  • @haim770 I have used the solution suggested by you but still getting null. Just wanted to know , what Liam is suggesting is it correct ? If it is then is there any alternative for the same? – Manoj Naik Dec 05 '16 at 11:20
  • @ManojNaik, Of course he's correct. Client configuration should be your default. I assumed you have a very good reason why to embed the configuration in the class library. – haim770 Dec 05 '16 at 11:22
  • @haim770 I want to keep my configuration settings specific to class library project. Also, I want to use that class library in diff application with diff values. Due to the same I am trying above scenario. If there is no solution to the above scenario then I have to find alternate any option for this. – Manoj Naik Dec 05 '16 at 11:37
  • @Liam and haim Thanks for your suggestions. Just wanted to know is there any option to close this Question? – Manoj Naik Dec 05 '16 at 11:38
  • 1
    @ManojNaik, Did you follow all the steps I described in the modified answer (including the rename)? Did you verify that the actual value of `Path.Combine(exeConfigPath, "ClassLibrary1.config")` corresponds to the correct path? – haim770 Dec 05 '16 at 11:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129797/discussion-between-manoj-naik-and-haim770). – Manoj Naik Dec 05 '16 at 11:45