0

App.config の読み取り/書き込みに問題があります。

以下のコードは、(AppSettingsSection クラス) http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.100%29.aspxに関する MSDN の記事から取得したものです。

App.config ファイルを正常に読み取り、値を取得/使用できます。App.config ファイルを変更して新しい値を取得すると、正しく応答します。

ただし、これ (MS ページから) では、新しいエントリを追加し、最初のエントリの 1 つの値を変更します。変更されているように見え、保存時にエラーは発生しませんが、ファイルに書き込まれないため、次回実行すると、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>
4

1 に答える 1

0

ソリューション エクスプローラー ウィンドウで app.config ファイルを右クリックし、[プロパティ] オプションを選択します。[出力ディレクトリにコピー]プロパティが[常にコピー] に設定されていないことを確認します。

于 2012-08-29T17:27:40.490 に答える