. Net does not provide a hosted class library for INI reading and writing. If you use INI, you must call an unmanaged API. One Nini provides a hosted class library.
Today, we will read and save the xml configuration file.
1. Collection class
First, we need a collection class to save the key and key value. It must provide both the key name and the index to find the key value. Therefore, we use the system. Collections. Specialized. namevaluecollection class. Note that the key value of this class can only be string.
Imports system. xml
Public class settingclass setting
Inherits system. Collections. Specialized. namevaluecollection
End Class
2. xml configuration file format
The configuration file format is app. config.
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "key1" value = "value1"/>
</Appsettings>
</Configuration>
3. Read the xml configuration file
Sub loadsetting () sub loadsetting (byval filepath as string)
Dim reader as xmltextreader
Try
Reader = new xmltextreader (filepath)
Reader. whitespacehandling = whitespacehandling. none' ignore the whitespace used
Me. Clear () 'clear all existing data
Catch ex as exception
Msgbox ("XML file not found" + ex. tostring)
Exit sub
End try
Try
While reader. Read
If reader. Name = "add" then
Dim key, value as string
Reader. movetoattribute ("key ")
Key = reader. Value
Reader. movetoattribute ("value ")
Value = reader. Value
Me. Set (Key, value)
Reader. movetoelement ()
End if
End while
Catch ex as exception
Msgbox ("XML file format error" + ex. tostring)
Exit sub
Finally
Reader. Close ()
End try
End sub
3. Write the xml configuration file
Sub savesetting () sub savesetting (byval filepath as string)
Dim writer as new xmltextwriter (filepath, system. Text. encoding. Default)
Writer. writestartdocument () 'writes the xml header
Dim I as integer
Writer. writestartelement ("configuration ")
Writer. writestartelement ("receivettings ")
For I = 0 to me. Count-1
Writer. writestartelement ("add ")
Writer. writestartattribute ("key", String. Empty)
Writer. writeraw (Me. getkey (I ))
Writer. writeendattribute ()
Writer. writestartattribute ("value", String. Empty)
Writer. writeraw (Me. Item (I ))
Writer. writeendattribute ()
Writer. writeendelement ()
Next
Writer. writeendelement ()
Writer. writeendelement ()
Writer. Flush ()
Writer. Close ()
End sub
BTW: Maybe you have to ask how these functions are useful. Yes, they are purely redundant in the full framework. However,. Net Cf ........