将app.config文件移动到自定义位置

时间:2011-01-25 17:28:15

标签: .net vb.net configuration

我的应用程序是一个服务应用程序,它需要加载一组用户可以更改的配置。我正在使用System.Configuration类来设置app.config文件,然后我将为用户提供编辑此文件以更改配置的选项。

我可以将此文件移动到自定义目录,例如C:\ settings \ app.config吗?还是被迫驻留在app目录中?

谢谢

3 个答案:

答案 0 :(得分:2)

看一下这个链接:

How to read app.config from a custom location, i.e. from a database in .NET

特别是这个答案:

What about using:

System.Configuration.ConfigurationManager.OpenExeConfiguration(string exePath)
That should let you open an arbitrary app.config file.

答案 1 :(得分:1)

您现在看到的文件app.config将命名为myservice.exe.config,并且可以在可执行文件myservice.exe的同一文件夹中找到,因为我对Windows应用程序的了解与ASP.NET应用程序相反,当程序运行时,您无法手动编辑.config文件,将被锁定,如果您使用记事本打开它,则无法保存。即使你做了一些魔法来解锁它,你仍然应该停止并重新启动Windows服务以从那里获取最新的值。我不知道你是否可以将它放在另一个文件夹中,我猜不是。您仍然可以在一些其他文件,xml或数据库中保存所需的设置,例如,.config文件将包含一个带有这些自定义XML文件路径的密钥。

答案 2 :(得分:0)

另一种方法是将配置文件保留为可执行文件,并将相关的可更改部分移动到外部xml文件,这些文件可以位于您选择的任何位置。

如果您以只读容量使用配置文件,则可以使用XML Inlcude将相关块添加到不同位置的XML文件中。如果您尝试使用Configuration.Save方法将值直接写回app.config,那么这将无法工作。

的app.config:



<?xml version="1.0"?>
<configuration xmlns:xi="http://www.w3.org/2001/XInclude">
    <appSettings>
      <xi:include href="AppSettings.xml"/>
    </appSettings>
  <connectionStrings>
    <xi:include href="ConnectionStrings.xml"/>
  </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/></startup>
</configuration>
&#13;
&#13;
&#13;

ConnectionStrings.xml:

&#13;
&#13;
<?xml version="1.0"?>
<add name="Example1ConnectionString"
        connectionString="Data Source=(local)\SQLExpress;Initial Catalog=Example1DB;Persist Security Info=True;User ID=sa;Password=password"
        providerName="System.Data.SqlClient" />
<add name="Example2ConnectionString"
        connectionString="Data Source=(local)\SQLExpress;Initial Catalog=Example2DB;Persist Security Info=True;User ID=sa;Password=password"
        providerName="System.Data.SqlClient" />
&#13;
&#13;
&#13;

AppSettings.xml:

&#13;
&#13;
<?xml version="1.0"?>
<add key="Setting1" value="Value1"/>
<add key="Setting2" value="Value2"/>
&#13;
&#13;
&#13;

文件URI如下所示:

file:///C:/whatever.txt

您甚至可以定义故障转移文件,以防您尝试引用的文件丢失。此模式来自https://www.xml.com/pub/a/2002/07/31/xinclude.html

&#13;
&#13;
<xi:include href="http://www.whitehouse.gov/malapropisms.xml">
  <xi:fallback>
    <para>
      This administration is doing everything we can to end the stalemate in
      an efficient way. We're making the right decisions to bring the solution
      to an end.
    </para>
  </xi:fallback>
&#13;
&#13;
&#13;

相关问题