gpt4 book ai didi

c# - 在应用程序文件夹外读取单独的 web.config 文件

转载 作者:太空狗 更新时间:2023-10-29 23:12:27 26 4
gpt4 key购买 nike

我需要读取应用程序文件夹外(位于任何其他目录中)的 web.config 文件。我试过这段代码:

string filePath = @"C:\Users\Idrees\Downloads\New folder\Web.config";
Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath);
var value1 = c1.AppSettings.Settings["Key1"].Value;

但它给我错误:

Object reference not set to an instance of an object.

因为在这里,c1.AppSettings 是一个对象,但是 c1.AppSettings.Settings 不包含项目(因此 0 计数)。它并没有真正加载 AppSettings 键。尝试从 Settings 集合中读取任何 Key 时,会出现此错误。

有什么方法可以从应用程序文件夹外的 web.config 文件加载 AppSettings 键。

如果我将相同的文件放在应用程序文件夹中,那么它会成功读取 key 。

这是我的示例配置文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!--here goes my connection strings-->
</connectionStrings>
<appSettings>
<add key="Key1" value="Value1" />
<add key="Key2" value="Value2" />
<add key="Key3" value="Value3" />
</appSettings>

</configuration>

我的服务器上已经运行了一个 Web 应用程序。我需要开发一个小实用程序,它必须在数据库中做一些工作,我不想在每个应用程序中编写数据库凭据或连接字符串(以及其他一些额外的应用程序设置),我希望它读取相同的东西来自 web.config。

最佳答案

您可以使用 ConfigurationManager 通过打开映射 exe 配置来读取任意配置文件,如下所示:

var filePath = @"C:\Users\Idrees\Downloads\New folder\Web.config";
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var value = configuration.AppSettings.Settings["Key1"].Value;

关于c# - 在应用程序文件夹外读取单独的 web.config 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49378344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com