C# ConfigurationManager返回null而不是字符串值
我试图从我的App.config文件中检索值,该文件存储在我的工作目录中,但是当我运行该程序时,它返回null。我很困惑为什么会这样,并且已经检查了代码很多次,试图发现错误 以下是我的App.config文件代码:C# ConfigurationManager返回null而不是字符串值,c#,.net,app-config,configurationmanager,C#,.net,App Config,Configurationmanager,我试图从我的App.config文件中检索值,该文件存储在我的工作目录中,但是当我运行该程序时,它返回null。我很困惑为什么会这样,并且已经检查了代码很多次,试图发现错误 以下是我的App.config文件代码: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="provider" value="System.Data.SqlCli
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="provider" value="System.Data.SqlClient" />
</appSettings>
<connectionStrings>
<add name="connection" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Autos;Integrated Security=True;Pooling=False" />
</connectionStrings>
</configuration>
当我运行这段代码时,p=null和c=null
我引用了System.Configuration.dll。您是否确保配置文件正确放置在运行应用程序的目录中?该目录中是否有名为.exe.config的文件 我只是在这里猜测-也许你在另一个项目中添加了App.Config文件,然后是你的exe汇编项目 顺便说一下,我将您的代码和App.Config原样复制到了一个干净的项目中,这段代码对我很有用。所以我会看配置文件本身的方向,而不是代码。代码很好 希望这有帮助
运行如果所有设置都正确,但仍然得到空值,请检查app.config文件并按如下所示替换xml代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
</configuration>
现在运行代码,如果您的配置文件在不同的类库中使用,您可能会看到正确的值,您必须更改名称您的类库dllname.dll.config,并且必须更改配置文件复制到输出目录属性
Ex:
YourSolution
ClassLibrary_1
ClassLibrary_1.dll.config
ApplicationConfigurationReader.cs
ConfigurationConst.cs
ClassLibrary_2
ConsoleApp
如果调试文件夹中有.dll,我希望您可以获得干净的帮助,然后将confif文件重命名为yourprojectname.dll.config。这在我的案例中起到了作用您的app.config是否与可执行文件一起正确部署?。。IE:在执行目录中是否存在
ApplicationName.exe.config
文件?使用的模板是App.config。真正的配置文件将是“Program.Exe.config”文件。这应该在编译项目时完成。您是否有机会将配置添加到DLL项目中?我将App.config文件放在我的bin\Debug文件夹中,但是此文件夹以及与此项目关联的其他文件夹均不包含.exe.config文件。这是一个可执行文件,不是库。我已尝试清理和重建项目,但未显示此文件。您不应手动复制App.config文件。它应该在构建时自动复制和重命名。也许您只是在项目中添加了一个名为App.config的文件,而不是添加“应用程序配置”项?您可以尝试将其重新添加到可执行项目中。”也许您只是将名为App.config的文件添加到项目中,而不是添加“应用程序配置”项”才是正确答案。谢谢你,兰。
Ex:
YourSolution
ClassLibrary_1
ClassLibrary_1.dll.config
ApplicationConfigurationReader.cs
ConfigurationConst.cs
ClassLibrary_2
ConsoleApp
public static class ConfigurationConst
{
public static KeyValueConfigurationCollection Configs;
}
internal class ApplicationConfigurationReader
{
public void Read()
{
// read assembly
var ExecAppPath = this.GetType().Assembly.Location;
// Get all app settings in config file
ConfigurationConst.Configs = ConfigurationManager.OpenExeConfiguration(ExecAppPath).AppSettings.Settings;
}
}
static void Main(string[] args)
{
new ApplicationConfigurationReader().Read();
var Configval = ConfigurationConst.Configs["provider"].Value;
Console.ReadKey();
}