【发布时间】:2017-04-19 14:33:22
【问题描述】:
我正在尝试从 appSettings 读取值,但得到 null 值作为回报。还在我的类文件中的element 变量中获取null 值。下面是我的类文件内容。
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");
}
}
}
}
我的 app.config 文件如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="TestValue"/>
</appSettings>
</configuration>
对System.Configuration 的引用存在于我的类库项目中。我正在从同一解决方案的另一个项目中存在的一个 Windows 窗体中调用 GetDataAppConfig 窗体。
已编辑
我正在使用我的类库项目中的配置文件。
我的 WinForm 类如下,我用它来调用类库项目的 classClass1 中的 GetDataAppConfig。
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();
}
}
}
【问题讨论】:
-
尝试使用
AppSettingsSection而不是NameValueCollection。喜欢config.GetSection("appSettings").Settings[key].Value; -
@Liam 我不想使用客户端应用程序中存在的配置文件。
-
当然,即使您确实做到了这一点,添加到客户端应用程序的任何配置都会覆盖您自己的配置。基本上,不要这样做,你只是让自己头疼,你可以不这样做。
标签: c# visual-studio visual-studio-2012