徹底解決 user.config 文件損壞

症狀見 發生 Configuration system failed to initialize 錯誤的一個特例

解決的辦法,在去讀 user.settings 之前捕獲錯誤,比如 Main() 裏面先調用 UserConfigFixer.AutoCheck()

 1 Imports System.Configuration
 2 Imports System.IO
 3 
 4 Public Class UserConfigFixer
 5     Public Shared Sub AutoCheck()
 6         Try
 7             'My.Settings.Reload()
 8             Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
 9             Dim fullFileName = config.FilePath
10         Catch ex As ConfigurationErrorsException
11             fixCorruptUserConfigFile(ex)
12         End Try
13     End Sub
14 
15     Private Shared Sub fixCorruptUserConfigFile(ByVal ex As ConfigurationErrorsException)
16         Dim filename = ex.Filename
17 
18         If MessageBox.Show("檢測到您的用戶設置文件已損壞,這可能是由於衝突或不正確的退出造成的,需要重置用戶設置才能繼續。" & vbNewLine & vbNewLine _
19                            & "單擊【是】將自動重置用戶設置並繼續。” & vbNewLine & vbNewLine _
20                            & “如果要嘗試手動修復,請單擊【否】",
21                            "損壞的用戶設置",
22                             MessageBoxButtons.YesNo, MessageBoxIcon.Error) = DialogResult.Yes Then
23             File.Delete(filename)
24             'you could optionally restart the app instead
25             Application.Restart()
26             'avoid the inevitable crash
27         End If
28         Environment.Exit(-1)
29     End Sub
30 End Class

 

參考文獻

Handling Corrupt "user.config" Settings - CodeProject

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章