似乎没有什么好办法来解决这个问题,除了最笨的一种:
FileSystemWatcher watcher
=
new
FileSystemWatcher(directory,
"
*.txt
"
);
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += FileCreated;
watcher.EnableRaisingEvents = true ;
private void FileCreated( object sender, FileSystemEventArgs e)
{
while ( ! IsFileReady(e.FullPath))
{
if ( ! File.Exists(e.FullPath))
return ;
Thread.Sleep( 100 );
}
// 在这里进行文件处理。。。
}
bool IsFileReady( string filename)
{
FileInfo fi = new FileInfo(filename);
FileStream fs=null;
try
{
fs = fi.Open(FileMode.Open, FileAccess.ReadWrite,
FileShare.None);
return true ;
}
catch (IOException)
{
return false ;
}
finally
{
if(fs!=null)
fs.Close();
}
}
好在这个事件不是在主线程引发,所以线程等个几秒钟也不是太大的问题。
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += FileCreated;
watcher.EnableRaisingEvents = true ;
private void FileCreated( object sender, FileSystemEventArgs e)
{
while ( ! IsFileReady(e.FullPath))
{
if ( ! File.Exists(e.FullPath))
return ;
Thread.Sleep( 100 );
}
// 在这里进行文件处理。。。
}
bool IsFileReady( string filename)
{
FileInfo fi = new FileInfo(filename);
FileStream fs=null;
try
{
fs = fi.Open(FileMode.Open, FileAccess.ReadWrite,
FileShare.None);
return true ;
}
catch (IOException)
{
return false ;
}
finally
{
if(fs!=null)
fs.Close();
}
}