为了账号安全,请及时绑定邮箱和手机立即绑定

FileSystemWatcher 不触发 .Created on FileInfo.

FileSystemWatcher 不触发 .Created on FileInfo.

C#
湖上湖 2021-06-23 18:01:18
我正在尝试使用该FileSystemWatcher对象来监视目录,以了解何时创建新文件以维护实时存在的文件组合框。不幸的是,在代码中创建的文件不会触发附加到Created事件的事件处理程序。为什么这不起作用,我该怎么做才能使用该FileSystemWatcher对象使其工作?(我已经看到了这一点,并且宁愿不必依赖外部库来完成这项工作)。我所见过的FileSystemWatcher工作时,我右击- >创建新的文件,但我需要它的工作当程序调用.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。这就是我必须添加的内容才能看到正在创建的新文件。不是我所期望的,而是给出了我需要的结果。


查看完整回答
反对 回复 2021-06-27
  • 1 回答
  • 0 关注
  • 487 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信