为什么我在 App.config 中对 AppSettings 的更改在运行时没有被考虑在内?(控制台应用程序)

问题描述:

我有一个控制台应用程序,它有自己的 App.config.

I have a console application which has its own App.config.

我需要不时更改部分中的一些值.

I need to change some values in section time to time.

我的问题是,当我在 bin/debug 文件夹中执行 exe 时,它​​会正确获取相关的 appsettings.但是当我编辑和更改某些键/值对的值并重新运行 exe 时,它​​仍然读取原始值.

My problem is, when I execute the exe within the bin/debug folder it gets the relevant appsettings correctly. But when I edit and change values of some key/value pairs and RE-RUN the exe, it still reads the original values.

(重新运行是指通过调用 MyTool.exe 在命令提示符上运行应用程序)

(By RE-RUN I mean running the application on the command promt by calling MyTool.exe)

我试着打电话

ConfigurationManager.RefreshSection("appSettings");

在我的 Main 方法的开头.但没有帮助.

in the begining of my Main method. But did not help.

可以请教一下吗?谢谢

但是当我编辑和更改某些键/值对的值并重新运行时exe,它仍然读取原始值.

But when I edit and change values of some key/value pairs and RE-RUN the exe, it still reads the original values.

取决于您如何重新运行此 exe.如果您在 Visual Studio 中执行此操作,通过点击 F5,VS 只需将项目中的 app.config 文件复制到输出并将其重命名为 AppName.exe.config.因此,如果您希望将您的更改考虑在内,您必须修改 AppName.exe.config(而不是 App.config),然后从 Windows 资源管理器中运行可执行文件.

Depends how you are RE-RUNNing this exe. If you are doing this in Visual Studio, by hitting F5, VS simply copies the app.config file in your project to the output and renames it to AppName.exe.config. So if you want your changes to be taken into account you have to modify AppName.exe.config (not App.config) and then run the executable from the Windows Explorer.

话虽如此,App.config 只会被读取和解析一次.应用程序启动时.然后,这些值会被缓存,以避免每次您的应用程序请求某个值时进行昂贵的 XML 解析.

This being said, the App.config is read and parsed only once. When the application starts. The values are then cached to avoid expensive XML parsing everytime your application requests some value.

App.config 旨在存储不应更改的配置值.如果您需要动态更改配置值,您应该使用其他一些存储机制:文件、数据库、...

App.config is designed to store configuration values that are not supposed to be changed. If you need to change configuration values dynamically you should use some other storage mechanism: file, database, ...

但是 ConfigurationManager.RefreshSection("appSettings"); 方法应该可以工作.一旦你修改了 AppName.exe.config 文件,你调用这个方法,然后使用 ConfigurationManager.AppSettings["someKey"]; 重新获取你需要的值,它应该返回你是新的价值.

But the ConfigurationManager.RefreshSection("appSettings"); method should work. Once you have modified the AppName.exe.config file, you call this method and then refetch the value you need using ConfigurationManager.AppSettings["someKey"]; which should return you the new value.