首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将app.config文件移动到自定义位置

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

Stack Overflow用户
提问于 2011-01-26 01:28:15
回答 3查看 5.8K关注 0票数 1

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

是否可以将此文件移动到自定义目录,如C:\settings\app.config?或者它被强制驻留在app目录中?

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-26 02:05:37

看看这个链接:

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

特别是这个答案:

代码语言:javascript
运行
复制
What about using:

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

Stack Overflow用户

发布于 2011-01-26 01:37:05

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

票数 1
EN

Stack Overflow用户

发布于 2018-04-21 04:05:57

另一种方法是将配置文件与可执行文件一起保留,并将相关的可变节移动到外部xml文件中,外部xml文件可以位于您选择的任何位置。

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

app.config:

代码语言:javascript
运行
复制
<?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>

ConnectionStrings.xml:

代码语言:javascript
运行
复制
<?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" />

AppSettings.xml:

代码语言:javascript
运行
复制
<?xml version="1.0"?>
<add key="Setting1" value="Value1"/>
<add key="Setting2" value="Value2"/>

文件URI如下所示:

代码语言:javascript
运行
复制
file:///C:/whatever.txt

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

代码语言:javascript
运行
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4796801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档