读取/写入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中的初始值。
有人能告诉我错误的方法吗?
TIA!
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>
答案 0 :(得分:0)
右键单击解决方案资源管理器窗口中的app.config文件,然后选择属性选项。确保复制到输出目录属性未设置为始终复制。