2012-08-29 84 views
0

读取/写入App.config时出现问题。写入App.Config文件时出现问题

下面我有我从(AppSettingsSection类)MSDN文章 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

我知道创建的AppName.exe.config文件,但它们保持为App.config ...不变... – newby

+1

YouTube上的一个教程指出,从appConfig进行的READING是原生开箱即用的。 NET但写作不是... :( – newby

回答

0

右键点击你的解决方案资源管理器窗口中的app.config文件,并选择属性选项。确保复制到输出目录属性未设置为始终复制

+0

这是关于不要复制,但我尝试所有三个具有相同的效果。 – newby