在处理程序的两个实例时,我遇到了保存配置文件的问题。我能够在一个看起来像这样的简单示例项目中重现此问题:
Class MainWindow
Dim config As System.Configuration.Configuration
Public Sub New()
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None)
End Sub
Protected Overrides Sub OnClosing(e As CancelEventArgs)
config.Save(ConfigurationSaveMode.Modified, True)
End Sub
End Class
第一个实例是在关闭时保存配置,但是一旦我尝试关闭第二个实例,config.Save(ConfigurationSaveMode.Modified,True)就会抛出错误,说配置文件被其他程序更改了。我希望有人能够帮助我解决这个问题。提前谢谢。
编辑:忘记删除MyBase调用
edit2:尝试过Chillzy建议,但也失败了。
Protected Overrides Sub OnClosing(e As CancelEventArgs)
Dim mdate As String = Date.Now.ToString("yyyyMMdd_HHmmss")
Dim mptpath As String = Path.GetDirectoryName(config.FilePath) & "\" & mdate
config.SaveAs(mdate, ConfigurationSaveMode.Full, True)
File.Delete(fpath)
File.Move(mptpath, fpath)
End Sub
答案 0 :(得分:0)
通过在OnClosing结束时调用OnClosing来进行循环
Protected Overrides Sub OnClosing(e As CancelEventArgs)
config.Save(ConfigurationSaveMode.Modified, True)
End Sub
答案 1 :(得分:0)
有。您复制加载配置文件,然后另存为。重新读取saveas文件作为当前配置文件。在你出去的路上你做反向
Imports System.Configuration
Imports System.IO
Public Class Form1
Dim config As System.Configuration.Configuration
Dim fpath As String = ""
Dim mptpath As String = ""
Public Sub New()
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None)
fpath = config.FilePath
Dim mdate As String = Date.Now.ToString("yyyyMMdd_HHmmss")
mptpath = Path.GetDirectoryName(config.FilePath) & "\" & mdate & ".config"
config.SaveAs(mptpath, ConfigurationSaveMode.Full, True)
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(mptpath)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
File.Delete(fpath)
config.SaveAs(fpath, ConfigurationSaveMode.Full, True)
File.Delete(mptpath)
End Sub
End Class