读取/写入 App.config 时出现问题。
下面的代码来自 MSDN 文章(AppSettingsSection 类) http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.100%29.aspx
我能够成功读取 App.config 文件并获取/使用这些值,如果我更改 App.config 文件以获取新值,它会正确响应。
但是,在此(来自 MS 页面)中,我添加了一个新条目并更改了我的一个初始条目的值。它似乎改变了它,保存它没有错误,但没有将它写入文件,所以下次我运行时,我会回到 App.config 中的初始值。
有人可以告诉我我的错误方式吗?
蒂亚!
Imports System
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Text
Imports System.IO
' IMPORTANT: To compile this example, you must add to the project
' a reference to the System.Configuration assembly.
'
Module Module1
Sub Main()
Dim KeypairHolder As String = Nothing
' Get Configuration File as config object
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' Create a unique key/value pair to add to the appSettings section.
Dim keyName As String = "DateTimeStamp Number " & config.AppSettings.Settings.Count + 1
Dim value As String = String.Concat(Date.Now.ToLongDateString(), " ", Date.Now.ToLongTimeString())
' Create appSettings as object
Dim appSettings As System.Configuration.AppSettingsSection = config.AppSettings
' add the new key and value
appSettings.Settings.Add(keyName, value)
' save and refresh the values
config.Save(ConfigurationSaveMode.Modified)
' Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings")
' Get keys
Dim kAll() As String = appSettings.Settings.AllKeys()
' Build string to display
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
'Display
MsgBox(KeypairHolder)
' Change a value
appSettings.Settings("CustomKey").Value = "Changed Value"
' Resave and get and display
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
kAll = appSettings.Settings.AllKeys()
KeypairHolder = Nothing
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
MsgBox(KeypairHolder)
End Sub
End Module
' appSettings Section of my App.Config file
' <appSettings>
' <add key="UsernamePassword" value="BobsUsername:BobsPassword"/>
' <add key="CustomKey" value="ConfigApp Value"/>
' </appSettings>