FileSystemWatcher的行为不一致
本文关键字:不一致 FileSystemWatcher | 更新日期: 2023-09-27 18:29:37
我已经在设计器中设置了所有FSW属性(EnableRaisingEvents=true,filter=*.tif,IncludeSubdirectories=true,path=bla''bla''bla)。
该应用程序在Windows Server 2008 R2 Standard计算机上运行,并监视本地文件夹中创建的文件。我使用计算机网络名称"GRAHAM"而不是"C:''"。
问题是,当文件被创建/移动到监视目录时,FSW并不总是启动。似乎有时会,但大多数时候不会。
在我的机器上调试和查看该文件夹时,也会出现一些奇怪的行为。如果我远程控制服务器机器并将文件移动到监视的文件夹,则不会发生任何事情。但是,如果我将文件从共享网络文件夹移到受关注的文件夹中,FSW每次都会启动。
这让我很难找到错误/bug。有人有什么想法吗?
这就是代码的全部:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Ekonomikompetens_unikt_namn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
StringBuilder log = new StringBuilder();
try
{
log.Append("--------------------").AppendLine().Append(DateTime.Now).AppendLine().Append("--------------------").AppendLine();
FileInfo file = new FileInfo(e.FullPath);
while (IsFileLocked(file))
{
System.Threading.Thread.Sleep(300);
}
string oFile = e.FullPath;
string nFile = oFile.Insert(oFile.Length - 4, "_" + DateTime.Now.ToString().Replace(" ", "").Replace("-", "").Replace(":", "")).Replace("''XML Konvertering", "").Replace(@"''GRAHAM'AnyDoc Invoices", @"''FAKTURASERVER'AnyDoc");
if (!Directory.Exists(nFile.Substring(0, nFile.LastIndexOf(''''))))
{
Directory.CreateDirectory(nFile.Substring(0, nFile.LastIndexOf('''')));
File.Move(oFile, nFile);
Directory.Delete(oFile.Substring(0, oFile.LastIndexOf('''')));
}
else
{
File.Move(oFile, nFile);
}
log.Append("* Moved and stamped file: ").AppendLine().Append(oFile).Append(" to ").Append(nFile).AppendLine().Append("--------------------").AppendLine();
}
catch (Exception x)
{
log.AppendLine().Append("*** ERROR *** ").Append(x).AppendLine().AppendLine();
}
finally
{
TextWriter tw = new StreamWriter(@"C:'tidslog'log.txt", true, Encoding.Default);
//TextWriter tw = new StreamWriter(@"C:'PROJEKT'tidsstämplarn'log.txt", true, Encoding.Default);
tw.Write(log);
tw.Dispose();
}
}
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
}
}
注意:try-catch finally可能做得不太好,但我是编码新手,不太确定如何"捕获"东西,不过记录器从未记录过错误。由于FSW从不开火,因此不会发生错误。我猜。
订阅错误事件并检查错误(如果有)
如果有大量文件正在创建或更改,请执行此
1>增加InternalBufferSize。
医生这样说:
增加缓冲区的大小可以防止丢失文件系统变更事件。然而,增加缓冲区大小是昂贵的,因为它来自无法交换到磁盘的非分页内存,因此保持缓冲区尽可能小。若要避免缓冲区溢出,请使用要筛选出的NotifyFilter和IncludeSubdirectories属性不需要的更改通知。
2>此外,您在fileSystemWatcher1_Created
中做了很多事情,这些事情可能会导致缓冲区溢出,从而导致它错过一些事件。。。请改用ThreadPool。