彻底解决 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

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