Skip to main content
 首页 » 编程设计

c#之在Web和控制台应用程序之间共享配置文件

2024年01月22日26dflying

我有一个Core类库,里面包含了我所有的逻辑。

我有一个使用IIS的Web应用程序。

我有一个使用Http侦听器的控制台应用程序。

两个主机项目都引用其中具有connectionStringSource.config文件的Core库。

主机项目已使用“添加为链接”到Core中的connectionStringSource.config并设置为“复制到输出”。在IIS主机项目的web.config中,它具有

<connectionStrings configSource="bin\connectionStringSource.config"></connectionStrings> 


但是我得到:


  [ArgumentException:路径中的非法字符。]
  [ConfigurationErrorsException:configSource属性无效。:路径中的非法字符。 (第13行)


如果我更改为

<connectionStrings configSource="bin/connectionStringSource.config"></connectionStrings> 


它说


  configSource属性必须是相对物理路径,因此不允许使用'/'字符。


是否可以共享这些设置?

我遵循了 here和 here的建议,但它们似乎没有用。

请您参考如下方法:

将connections.config文件添加到SolutionItems解决方案文件夹



就我而言,它包含

<connectionStrings> 
  <add name="MyContext" 
       connectionString="Data Source=Server\NamedInstance;Initial Catalog=MyDB;Integrated Security=True;MultipleActiveResultSets=True" 
    providerName="System.Data.SqlClient" /> 
</connectionStrings> 


单击任何项​​目并编辑app.config或web.config

<connectionStrings configSource="connections.config"></connectionStrings> 


现在单击项目,然后选择添加现有项,然后通过单击添加为链接将connections.config添加为链接。



现在,右键单击该项目,然后选择“卸载项目”



现在单击项目,然后选择编辑项目



您将看到以下内容:

  <ItemGroup> 
        <None Include="..\connections.config"> 
          <Link>connections.config</Link> 
        </None> 
        <None Include="App.config" /> 
      </ItemGroup> 


为了能够引用此文件,我们需要说复制链接的内容文件以滚动到底部并添加

 <Target Name="CopyLinkedContentFiles" BeforeTargets="Build"> 
    <Copy SourceFiles="%(Content.Identity)" DestinationFiles="%(Content.Link)" SkipUnchangedFiles="true" OverwriteReadOnlyFiles="true" Condition="'%(Content.Link)' != ''" /> 
  </Target> 


重新加载项目。



对您需要共享connections.config的项目重复上述步骤。

您可以具有connections.release.config。然后在您的Web.Release.config中添加

 <connectionStrings xdt:Transform="SetAttributes" configSource="connections.release.config" />