System.IO.FileSystemWatcher与文件的打开状态
2007-09-26 18:49
369 查看
使用System.IO.FileSystemWatcher时,通常会想在检测到文件创建之后,扫描文件的内容,对之进行一定的处理。但是当我们的程序接到通知时,创建文件的进程可能还在写数据,这时如果想要打开这个文件会抛出异常。
似乎没有什么好办法来解决这个问题,除了最笨的一种:
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();
}
}
好在这个事件不是在主线程引发,所以线程等个几秒钟也不是太大的问题。
似乎没有什么好办法来解决这个问题,除了最笨的一种:
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();
}
}
好在这个事件不是在主线程引发,所以线程等个几秒钟也不是太大的问题。
相关文章推荐
- System.IO.FileSystemWatcher 监视目录文件的状态
- System.IO.FileSystemWatcher 监视目录文件的状态
- System.IO.FileSystemWatcher 监视目录文件的状态
- 当更改指定 System.IO.FileSystemWatcher.Path 中的文件和目录时发生某个处理
- 使用FileSystemWatcher捕获系统文件状态
- C# FileSystemWatcher 在监控文件夹和文件时的用法概述
- C#中FileSystemWatcher控件实现文件监控
- n unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module.Additional information: 未能加载文件或程序集“..
- System.IO.FileSystemWatcher 类
- System.IO.FileLoadException: 未能加载文件或程序集 访问拒绝 解决方案之一
- C# System.IO.FileStream 文件正由另一进程使用,因此该进程无法访问该文件
- System.IO.FileNotFoundException: 未能加载文件或程序集“Microsoft.Office.Interop.Excel, Version=11.0.0.0, Cultur
- 使用FileSystemWatcher监视文件变化
- 使用文件监控对象FileSystemWatcher实现数据同步
- 利用FileSystemWatcher监控对文件的操作
- IIS目录下文件共享后System.IO.File.Exists返回false
- 使用FileSystemWatcher监测大文件时,如何判断文件已经创建完成?
- 关于文件结构体FILE中的成员,以及如何通过文件句柄判断文件是打开还是关闭状态
- System.IO.File.Exist(filePath)判断另外一台服务器上某个文件是否存在
- FileSystemWatcher 做文件同步几个问题