FileSystemWatcher未在FileInfo.Create()

时间:2018-05-21 22:15:56

标签: c# filesystemwatcher

我试图使用FileSystemWatcher对象来查看创建新文件时的目录,以维护实时存在的文件组合框。

不幸的是,在代码中创建的文件没有触发附加到Created事件的事件处理程序。

为什么这不起作用,我可以使用FileSystemWatcher对象做些什么来使它工作? (我已经看过this而宁愿不依赖外部库来完成这项工作。)

当我右键单击时,我看到FileSystemWatcher工作了 - >创建新文件,但是当程序在.Create( )对象上调用FileInfo时,我需要它才能工作。

符合Minimal, Complete, and Verifiable Example要求:

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]属性的原因是因为我注意到它here,并认为它可能是问题(事实并非如此)。

1 个答案:

答案 0 :(得分:1)

试试NotifyFilters.FileName。这就是我必须添加以查看正在创建的新文件。不是我的预期,而是给出了我需要的结果。