我正在尝试使用
FileSystemWatcher
当创建新文件以维护实时存在的文件组合框时,要监视目录的对象。
不幸的是,在代码中创建的文件没有激发附加到
Created
事件。
为什么这不起作用,我该怎么做才能使它起作用,使用
文件系统监视程序
对象?(我见过
this
而不必依赖外部库来实现这一点)。
我看到了
文件系统监视程序
右键单击时工作--创建新文件,但程序调用时需要它工作
.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
并认为这可能是问题所在(事实并非如此)。