资讯详情

FileSystemWatcher 读取文件时出现被占用的解决方法

今天,做一个小程序监控目录,序列化XML当第一次正常,第二个新文件被占用时,记录解决方案。

 1 FileSystemWatcher watcher = new FileSystemWatcher{  2                 Path = path,  3                 Filter = filter,  4                 EnableRaisingEvents = true,  5                 IncludeSubdirectories = true,  6                 NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName |  7                     NotifyFilters.FileName | NotifyFilters.LastAccess  8                     | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size  9             }; 10             watcher.Created  = OnCreated; 11  12 private static void OnCreated(object source, FileSystemEventArgs e) 13         { 14             Console.WriteLine("Got a new file "   e.Name); 15  16                 #region === 阅读文件内容 === 17                 string xmlStr = string.Empty; 18                 while (true) 19                 { 20                     try 21                     { 22                         using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) 23                         { 24                             if (stream != null) 25                                 break; 26                         } 27                         System.Threading.Thread.Sleep(500); 28                     } 29                     catch (Exception ex) 30                     { 31                         Console.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.Name, ex.Message)); 32                     } 33                 } 34                   using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 36  { 37                     using (StreamReader sr = new StreamReader(fs, Encoding.Default)) 38  { 39                         xmlStr = sr.ReadToEnd(); 40  } 41  } 42                 #endregion
43         }

主要原因是文件还在写入过程中,还被占用,所以不能读取,以下代码为核心解决方法:

while (true)
                 {
                     try
                     {
                         using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                         {
                             if (stream != null)
                                 break;
                         }
                         System.Threading.Thread.Sleep(500);
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.Name, ex.Message));
                     }
                 }

 提示:如果是以windows 服务的形式访问网络文件时,不能通知映射盘符的方式,必须是以IP或者hostname方式,比如不能是Z:\\abc\,必须为\\192.168.1.2\abc\

标签: 200v1800uf铝电解电容

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台