我有点用你的2号。
但我只在 .NET 2 中使用我的应用程序,但它应该仍然适用。
我有一个在两个程序中使用的设置类。在这个设置类中我设置了一个文件系统观察者查看设置文件的对象。
如果其他应用程序更新了设置文件,我的当前应用程序会收到一个事件触发器来指示需要重新加载设置。
您还可以在设置屏幕中应用相同的原则,以便如果(服务)其他应用程序在设置编辑期间更新任何内容,则会反映在您的屏幕中。
我使用AppData(我的公司/应用程序名称目录)来存储文件。
另一件要记住的事情是,在写入文件时可以对文件进行锁定,因此您可以使用临时名称保存、删除旧的、重命名临时方法,或者在写入后读取文件时对文件进行一些保护性锁定。 filewatcher 事件触发已进行更改。
我在我的文件系统观察者在继续之前
IPSDependency.FileSystem.WaitForLockOnFile(Me.mFilePath)
其代码是这样的。 (现在阅读本文后,可能有更好的方法,我在这里使用一些睡眠来减少 CPU 抖动)
Public Shared Function IsLockAvailable(ByVal filename As String, ByVal fnfIsOK As Boolean) As Boolean
Dim fi As FileInfo
fi = New FileInfo(filename)
Return IsLockAvailable(New FileInfo(filename), fnfIsOK)
End Function
Public Shared Function IsLockAvailable(ByVal theFile As FileInfo, ByVal fnfIsOK As Boolean) As Boolean
Dim fs As FileStream
Try
If theFile.Exists Then
fs = New FileStream(theFile.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
fs.Close()
Return True
Else
Return fnfIsOK
End If
Catch ex As IOException
'we just let the exception go, because we are only testing the file rather than trying to use it.
Return False
End Try
End Function
Public Shared Sub WaitForLockOnFile(ByVal theFilename As String)
WaitForLockOnFile(New FileInfo(theFilename))
End Sub
Public Shared Sub WaitForLockOnFile(ByVal theFile As FileInfo)
Dim lockAvailable As Boolean
If theFile.Exists Then
While Not lockAvailable
lockAvailable = IsLockAvailable(theFile, False)
End While
End If
End Sub