Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c# - Reload configuration settings from an external config file during run-time

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.

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.

What should I use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 provided by CarelZA:

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.

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"/>

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

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...