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

Read separate web.config file outside the application folder

我需要读取 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 密钥。

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

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

<?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.OpenExeConfiguration on MSDN

public static Configuration OpenExeConfiguration(
    string exePath
)

This is EXE path

您可以使用ConfigurationManager通过打开mapped 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;

据我从您的评论中了解到,您希望在同一台计算机上的多个应用程序之间进行某种共享配置。您可以考虑使用这样的外部文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <connectionStrings configSource="config\connString01.config"/>

  <appSettings file="config\config01.config">
    <add key="Var3" value="Var3 value from main config file"/>
  </appSettings>

在上面的 .config 示例中,connectionStrings 来自另一个文件。下面的示例可以是这样的外部配置文件:

<connectionStrings>
  <add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
</connectionStrings>