我正在嘗試使用該FileSystemWatcher對象來監(jiān)視目錄,以了解何時創(chuàng)建新文件以維護實時存在的文件組合框。不幸的是,在代碼中創(chuàng)建的文件不會觸發(fā)附加到Created事件的事件處理程序。為什么這不起作用,我該怎么做才能使用該FileSystemWatcher對象使其工作?(我已經看到了這一點,并且寧愿不必依賴外部庫來完成這項工作)。我所見過的FileSystemWatcher工作時,我右擊- >創(chuàng)建新的文件,但我需要它的工作當程序調用.Create( )一個的FileInfo對象。符合最小、完整和可驗證示例要求:using System;using System.IO;using System.Security.Permissions;namespace MCVEConsole { class Program { [PermissionSet( SecurityAction.Demand, Name = "FullTrust" )] static void Main( string[] args ) { DirectoryInfo myDirectory = new DirectoryInfo( Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ) ).CreateSubdirectory( "MCVEConsole" ); FileSystemWatcher fSW = new FileSystemWatcher( myDirectory.FullName, "*.txt" ) { NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite }; fSW.Created += new FileSystemEventHandler( _Changed ); fSW.Deleted += new FileSystemEventHandler( _Changed ); fSW.EnableRaisingEvents = true; new FileInfo( Path.Combine( myDirectory.FullName, "foo.txt" ) ).Create( ).Close( ); void _Changed( object sender, FileSystemEventArgs e ) => Console.WriteLine( "bar" ); Console.WriteLine( "Press any key to continue..." ); Console.ReadKey( ); } }}[PermissionSet]屬性的原因是因為我在這里注意到它,并認為它可能是問題(它不是)。
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
試試NotifyFilters.FileName
。這就是我必須添加的內容才能看到正在創(chuàng)建的新文件。不是我所期望的,而是給出了我需要的結果。
- 1 回答
- 0 關注
- 627 瀏覽
添加回答
舉報
0/150
提交
取消