2012-02-06 86 views
1

我正在使用以下代碼來替換我的app.config中的密碼。它會成功替換,但不會重新加載內存中的配置文件,因此數據集會給出錯誤的密碼錯誤。 請幫助使用替換方法更改密碼

Dim vrTextFind As String = "Password" 
    Dim vrTextReplaceWith As String = "PWD" 
    Dim path As String = "D:\VS2008\EncTest\EncTest\bin\Debug\enctest.exe.config" 
    Dim readText As String = File.ReadAllText(path) 
    TextBox1.Text = readText 
    'Find 
    Dim idx As Integer = 0 
    idx = TextBox1.Text.IndexOf(vrTextFind, idx) 
    If idx = -1 Then 
     MessageBox.Show(vrTextFind & " is not in Textbox1") 
    Else 
     TextBox1.SelectionStart = idx 
     TextBox1.SelectionLength = vrTextFind.Length 
    End If 
    'Replace 
    If TextBox1.Text.Contains(TextBox1.Text) Then 
     TextBox1.Text = TextBox1.Text.Replace(vrTextFind, vrTextReplaceWith) 
    Else 
     MessageBox.Show(TextBox1.Text & " is not in Textbox3") 
    End If 
    ''''' 
    'Write all back 
    File.WriteAllText(path, TextBox1.Text) 
    'Refreshes the connection string section 
    ConfigurationManager.RefreshSection("connectionStrings") 
+0

是您使用的密碼,是連接字符串的密碼? 爲什麼刷新節連接字符串? textbox1.text是否包含連接字符串? – Harsh 2012-02-06 13:12:38

回答

1

在Windows應用程序app.config是隻讀一次,應用程序啓動時。如果你修改它,你將需要重新啓動應用程序。

建議

代替在一些其他的文件(如設置文件)在app.config存儲其存儲密碼。它可以在運行時修改和讀取。對於Settings,您可以在MSDN上閱讀。並選擇User-Scope設置。

希望這可以幫助你。

+1

謝謝,但ConfigurationManager.RefreshSection(「connectionStrings」)是什麼意思?這可以再讀一遍嗎? – 2012-02-06 12:13:46

+0

嘗試使用控制檯應用程序,但未刷新連接字符串。但爲ConfigurationManager.RefreshSection +1。 – 2012-02-06 12:25:03

0

代替使用File.WriteallText使用下面的代碼寫入的app.config組成:

config.AppSettings.Settings.Item("ConnectionString").Value = TextBox1.Text 
    config.Save(ConfigurationSaveMode.Modified) 
    ConfigurationManager.RefreshSection("AppSettings") 

然後再次裝入從app.config中的連接字符串值。

Dim config As System.Configuration.Configuration 
Dim fileMap As New ExeConfigurationFileMap() 

fileMap.ExeConfigFilename = "Path of app.config" 
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None) 

' Sets values to config file. 
If config.HasFile() Then 

    strConnString = config.AppSettings.Settings.Item("ConnectionString").Value 

End If 
+0

如何重新加載連接字符串值? ConfigurationManager.RefreshSection(「AppSettings」)做到了嗎? – 2012-02-06 14:40:46

+0

看到我更新的答案。 只需從app.config中獲取值並將其放入一個變量並使用它。 – Harsh 2012-02-06 14:49:25