FileSystemWatcher 不触发 .Created on FileInfo.

我正在尝试使用该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]属性的原因是因为我在这里注意到它,并认为它可能是问题(它不是)。


湖上湖
浏览 595回答 1
1回答

MMTTMM

试试NotifyFilters.FileName。这就是我必须添加的内容才能看到正在创建的新文件。不是我所期望的,而是给出了我需要的结果。
打开App,查看更多内容
随时随地看视频慕课网APP