2012-01-22 92 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