在运行时重新加载从外部配置文件配置设置配置文件、加载

2023-09-02 23:43:45 作者:你的人比你的旧鞋还破^

我写在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

使用自定义配置节,通过设置部分的位置ATTRIB联播从在app.config到外部配置文件(S)的章节。所有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

所提供的code CarelZA :的

首先,ConfigurationManager中缓存应用程序的配置通过配置部分,你可以调用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文件和设置复制到输出目录,以复制总是

在game.config:

In game.config:

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

然后在code,以访问任何设置:

Then in code, in order to access any setting:

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

和重新加载游戏的配置在任何时候reload命令发送到服务器:

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

ConfigurationManager.RefreshSection("gameSettings");