在运行时从外部配置文件重新加载配置设置 [英] Reload configuration settings from an external config file during run-time

查看:49
本文介绍了在运行时从外部配置文件重新加载配置设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 编写游戏服务器,并希望在服务器运行时重新加载或刷新配置文件中的设置.

I'm writing a game server in C# and would like to reload or refresh settings from a config file while the server is running.

理想情况下,我想将设置保存在 XML 文件中,并能够编辑游戏服务器运行时的文件,然后向服务器发送重新加载的命令文件中的设置.

Ideally I would like to save the settings in an XML file, have the ability to edit the file while the game server is running and then send the server the command to reload the settings from the file.

我知道我也可以使用数据库来执行此操作,但游戏服务器相当小,我认为将设置保存在平面文件中会更实用.我将拥有对运行服务器的机器的文件级访问权限.

I know I can use a database to do this as well, but the game server is fairly small and I think it would be more practical to just save settings in a flat-file. I will have file-level access to the machine the server will run on.

我应该用什么?

推荐答案

使用 http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

使用自定义配置部分,通过设置部分的位置属性,将 app.config 中的部分连接到外部配置文件.所有 xml 加载和序列化都由那些自定义类完成

Use a Custom Configuration Section, hookup the sections from the app.config to external config file(s) by setting the location attrib of the section. All xml loading and serialization is done by those custom classes

代码由 CarelZA 提供:

首先,ConfigurationManager 通过 config 部分缓存应用程序的配置,您可以调用 ConfigurationManager.RefreshSection() 使特定部分的缓存无效.

First of all, ConfigurationManager caches the application's configuration by config section, and you can call ConfigurationManager.RefreshSection() to invalidate the cache for a specific section.

在 app.config 中我添加了:

In app.config I added:

<configSections>
  <section name="gameSettings" 
           type="System.Configuration.NameValueSectionHandler,system , Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
</configSections>
<gameSettings configSource="game.config"/>

我创建了一个名为game.config"的文件,并将复制到输出目录"设置为始终复制".

I created a file called "game.config" and set "Copy to Output Directory" to "Copy always".

在 game.config 中:

In game.config:

<gameSettings>
  <add key="SettingName" value="SettingValue" />
</gameSettings>

然后在代码中,为了访问任何设置:

Then in code, in order to access any setting:

settings = (NameValueCollection) ConfigurationManager.GetSection("gameSettings");
return settings["SettingName"];

并在重新加载命令发送到服务器时随时重新加载游戏配置:

And to reload the game config at any time when the reload command is sent to the server:

ConfigurationManager.RefreshSection("gameSettings");

这篇关于在运行时从外部配置文件重新加载配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆