c# - 配置系统初始化失败,外部配置文件

标签 c# .net config

我的 app.config 文件有问题。当配置文件位于exe文件旁边时,它就可以正常工作。
但是当我将外部配置文件放置到另一个网络驱动器时,它会抛出“配置系统无法初始化”错误。
我应该如何从应用程序配置链接到外部配置文件以使其正常工作?

这是代码:

Program.cs
static void Main(string[] args)
{
   var conn = ConfigurationManager.ConnectionStrings["conn"];
   Console.WriteLine("ConnStr01={0}", conn);
   Console.Read();
}

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings configSource="U:\config\conStr.config">
  </connectionStrings>
</configuration>

conStr.config
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
  <add name="conn"
    connectionString="Data Source={server};Initial Catalog={database};Persist Security Info=True;User ID={username};Password={password}"
    providerName="System.Data.SqlClient"/>
</connectionStrings>

最佳答案

  1. 不要使用文件属性,使用configSource - 因为文件仅适用于appSettings。对于 appSettings 来说也是如此:ConfigSource 是完全替换(没有合并)
  2. configSource 必须引用与配置文件位于同一目录或子目录中的文件。

ASP.NET web.config: configSource vs. file attributes

关于c# - 配置系统初始化失败,外部配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55276492/

相关文章:

c# - 将查询从 linq 复制到 Datatable 时出错

c# - 如何在 EF Core 3.1 中以异步方式使用 GroupBy?

grails - 如何在 grails 中扩展每个环境的配置

Android:配置更改未更新

C# 在派生类属性覆盖中使用基类属性值

c# - Xamarin CollectionView 缓慢滚动

c# - 为什么我们在 LINQ 中需要 Single()?

c# - 调试时静态变量初始值设定项的运行时评估异常

c# - Unity.MVC 无法使用参数解析我的 Controller 构造函数

Tomcat conf 文件夹位置更改?