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

本文介绍了一种使用FileSystemWatcher监测文件系统变化,并在文件创建完成后进行处理的方法。通过循环检查并等待文件写入完成,确保后续操作的正确性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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();
            }
        }
好在这个事件不是在主线程引发,所以线程等个几秒钟也不是太大的问题。
public class CustomerWatcher { System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(); List<string> currentpathList= new List<string>(); public void Watch(string Path) { watcher.Path = Path; watcher.NotifyFilter = System.IO.NotifyFilters.LastAccess | System.IO.NotifyFilters.LastWrite | System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName; watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged); watcher.Created += new System.IO.FileSystemEventHandler(OnCreated); watcher.Deleted += new System.IO.FileSystemEventHandler(OnChanged); watcher.Renamed += new System.IO.RenamedEventHandler(OnRenamed); watcher.EnableRaisingEvents = true; } private void OnChanged(object source, System.IO.FileSystemEventArgs e) { Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); string filePath = e.FullPath; List<string> filePathList = filePath.Split("\\").ToList(); int filePathListCount = filePathList.Count(); if (filePathListCount < 6) { return; } else if (filePathListCount > 6) { for(int i= filePathListCount - 1;i>=6;i--) { filePathList.RemoveAt(i); } } string productRootPath = string.Join("\\", filePathList); if(currentpathList.Contains(productRootPath)) { return; } int delayTime = 300; Thread.Sleep(delayTime); string cust_code=filePathList[2]; string cusr_code_short = cust_code.Split('(')[0]; if(cusr_code_short=="AZ") { } currentpathList.Add(productRootPath); }修改代码,中间这部分代码放到新的线程里面运行,不要阻塞主线程
最新发布
03-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值