简体   繁体   中英

Best way to write and modify config file in C#

I'm trying to write a small game in VisualStudio, C# language to improve and practice. The thing I'm trying to do is to have a config file that the user can edit with the settings menu in the game. I know I could write a simple .ini file and parse that when the program starts, but is there a better and simpler way to do it?

Just serialize/deserialize the whole class representing your settings to/from a file, that's the easiest to implement. You can use eg Json.NET

File.WriteAllText(@"C:\config.json", JsonConvert.SerializeObject(settings));

var settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(@"C:\config.json"));

1- Add an Application Configuration File to your project (right click project > add item). This will be called app.config inside your project. 2- Add Parameter to the file by :

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 

config.AppSettings.Settings.Add("Yourkey","Value");
config.Save(ConfigurationSaveMode.Minimal);

3 - Retrieve Data:

Configuration config = 
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string Value = config.AppSettings.Settings["Yourkey"].Value

You can use a the integrated settings functionality in .NET Framework in the System.Configuration namespace. To create a settings file, you need to add one in visual studio via the add element dialog. Select "Settings" an give it a name. Add settings file to yout project

Then you need to add settings to the file. There is a nice gui editor when you doble click on the file in solution explorer: Add settings to file

To access the values in code, you need get an instace of the settings object via the static propertie calles "Default" in you settings class: Access settings value in code

Don´t forget to call MySettingsClass.Default.Save() to save changed values before you close your application.

There are much more features than read an save values withe this method. You can read more about it here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM