2012-01-22 58 views
0

我在试图解决如何查看文件夹以进行更改时遇到问题。这是我得到了多少:在VB.net/WPF中观看文件夹

Class MainWindow 

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _ 
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded 
    Dim Path As String = "C:\Temp" 

    ' Create a new FileSystemWatcher and set its properties. 
    Dim watcher As New FileSystemWatcher() 
    watcher.Path = Path 
    ' Watch for changes in LastAccess and LastWrite times, and 
    ' the renaming of files or directories. 
    watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName) 
    ' Only watch text files. 
    watcher.Filter = "*.txt" 

    ' Add event handlers. 
    AddHandler watcher.Changed, AddressOf OnChanged 
    AddHandler watcher.Created, AddressOf OnChanged 
    AddHandler watcher.Deleted, AddressOf OnChanged 
    AddHandler watcher.Renamed, AddressOf OnRenamed 

    ' Begin watching. 
    watcher.EnableRaisingEvents = True 

End Sub 

' Define the event handlers. 
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs) 
    ' Specify what is done when a file is changed, created, or deleted. 
    MsgBox("File: " & e.FullPath & " " & e.ChangeType) 
End Sub 

Private Shared Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs) 
    ' Specify what is done when a file is renamed. 
    MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath) 
End Sub 
End Class 

问题是当程序退出没有错误代码的文件夹中发生更改时。我已经阅读了一些相关的帖子,我知道它与线程安全有关。不过,我不知道如何让这个程序“线程安全”。任何人都可以给我一些建议吗?谢谢!

+0

崩溃什么?空引用? –

+0

没有抱歉,它不会“崩溃”,程序只是退出,没有错误信息 – qu1ckdry

+0

为了帮助在将来发现这种错误,请在“公共语言运行时例外”中设置“发生异常时中断”在Visual Studio的调试菜单下的异常...窗口。 – perfectionist

回答

3

我没有收到任何线程安全问题。 我认为这个问题是:

MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath) 

应该

MsgBox(String.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)) 
+0

显然这只会影响Renames。如果这不能解决问题,请指出您对临时目录中的文件执行什么操作,以防对问题产生影响。 – perfectionist

+0

嘿感谢这个改变,现在工作,不用退出重命名!我不敢相信我忽略了这一点。此外,我只会测试我检查过的代码的重命名功能,其他处理程序正在工作。 – qu1ckdry