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.
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();
}
}
}