System.IO.FileSystemWatcher与文件的打开状态

使用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();
            }
        }
好在这个事件不是在主线程引发,所以线程等个几秒钟也不是太大的问题。

posted on 2007-09-26 18:49  deerchao  阅读(1830)  评论(5编辑  收藏  举报