开发者

How is the logic behind storing program setting in text file like 'config.cfg'?

开发者 https://www.devze.com 2023-03-03 06:29 出处:网络
Often I see some software and specially games that store setting in a text file. I want to have same thing in my C# WinForms application too (I know it is possible to do with application settings for

Often I see some software and specially games that store setting in a text file. I want to have same thing in my C# WinForms application too (I know it is possible to do with application settings for both user and software side) Since I think it is easier for end user to deal with it.

So what 开发者_StackOverflow社区I need to know is how these settings files are being read and for example set the fields of a class.

Imagine I have a class that has the following fields:

private double vOffset = 0;
private bool Refresh = false;

And here will be my text file (lets say file is named "config.cfg"):

;This is a comment
Voltage Offset = 0.08
;Refresh Enable = 1 | Disable = 0
Refresh = 1

Would like to hear your ideas and propably some codes maybe! both for reading this file and updating class fields and also how to save or update this list from within the software.

Thanks.


Can you use standard .NET settings classes?

Advantages:
- you don't need to code for this
- you have UI to edit your default settings
- you reference settings in the code in a typed manner, like this Settings.Default.Test1.
- your settings will be stored in the application config file, which is in XML.

More details here: http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx.

How is the logic behind storing program setting in text file like 'config.cfg'?

In config file it would look like this:

  <setting name="Test2"
           serializeAs="String">
    <value>My string setting</value>
  </setting>

You might argue that XML is not easy to read for the end user. But I believe that users who understand what 'Voltage Offset' is, should not have issues reading/updating settings in xml file :).


Actually the easiest way for you to do it in a .net environment is to have xml settings file. Using an xmlserializer you can serialize an object to text and deserealize from text.

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Edit: also xmlserializer won't serialize private fields/properties, so you should use public properties to get the desired result.


The setting are usually stored in one of the common formats E.g. XML (very common now), INI (used to be common), LAU, ...

Serializing object to these formats or deserializing from them can be done with built in serializers (e.g. XmlSerializer in .NET), 3rd party ones or even propriety custom ones.

0

精彩评论

暂无评论...
验证码 换一张
取 消