c#FileSystemWatcher—每几秒钟引发数百个不必要的过度事件
我使用的是FileSystemWatcher类,我需要它来监视我插入的闪存驱动器中来自任何地方的任何创建或粘贴的文件。我每2秒钟刷新一次插入的驱动器列表(如果有新插入的驱动器),然后设置FileSystemWatcher.EnableRaisingEvents=true,然后在2秒钟后将其设置为“false”,然后再次刷新插入的驱动器列表等 刷新间隔为2秒时,情况如下:c#FileSystemWatcher—每几秒钟引发数百个不必要的过度事件,c#,events,filesystemwatcher,C#,Events,Filesystemwatcher,我使用的是FileSystemWatcher类,我需要它来监视我插入的闪存驱动器中来自任何地方的任何创建或粘贴的文件。我每2秒钟刷新一次插入的驱动器列表(如果有新插入的驱动器),然后设置FileSystemWatcher.EnableRaisingEvents=true,然后在2秒钟后将其设置为“false”,然后再次刷新插入的驱动器列表等 刷新间隔为2秒时,情况如下: 程序工作1秒,我将文件粘贴到闪存驱动器-FSW引发一个“创建”事件 程序运行3秒钟,我将文件粘贴到闪存驱动器-FSW引发两个“
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Management;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Threading;
private static FileSystemWatcher watcher1 = new FileSystemWatcher();
private static DriveInfo[] GetDrivesList()
{
DriveInfo[] DriveList = DriveInfo.GetDrives();
return DriveList;
}
static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
if (is_directory == false)
{
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
}
return false;
}
static void OnChanged(Object source, FileSystemEventArgs e)
{
FileInfo fileInfo = new FileInfo(e.FullPath);
FileInfo fileInfo2 = new FileInfo(@"D:\Shadow Copies.log");
if (Convert.ToString(e.ChangeType) == "Created")
{
Console.WriteLine("File: {0} has been {1}", e.FullPath, e.ChangeType);
file_copied = false;
int length = Convert.ToString(e.FullPath).Length;
String Path = "";
String FileName = "";
for (int i = length - 1; i >= 0; i--)
{
if (Convert.ToString(e.FullPath)[i] != '\\')
{
Path += Convert.ToString(e.FullPath)[i];
}
else
{
break;
}
}
for (int i = Path.Length - 1; i >= 0; i--)
{
FileName += Path[i];
}
for (int i = FileName.Length - 1; i >= 0; i--)
{
if (FileName[i] == '.')
{
is_directory = false;
break;
}
}
string path = Convert.ToString(e.FullPath);
while (IsFileLocked(fileInfo) == true)
{
Thread.Sleep(100);
Console.WriteLine("Retrying in 1 sec...");
}
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.FileName = "cmd.exe";
psi.Arguments = @"/c xcopy " + path + @" D:\ShadowCopies\ /s /y";
Process proc = Process.Start(psi);
file_copied = true;
Console.WriteLine("File: {0} has been Copied", e.FullPath);
DateTime datetime = DateTime.Now;
CandidateLine = e.FullPath;
write_to_log = String.Format("{0} File: {1} has been Copied\r\n", datetime.ToString(), e.FullPath);
if (CandidateLine == LastLineWritten)
return;
while (IsFileLocked(fileInfo2) == true)
{
Thread.Sleep(100);
Console.WriteLine("Retrying...");
}
File.AppendAllText(@"D:\Shadow Copies.log", write_to_log);
LastLineWritten = CandidateLine;
is_directory = true;
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.CreateNoWindow = true;
psi2.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi2.FileName = "cmd.exe";
psi2.Arguments = "/c for /d %F in (D:\\ShadowCopies\\*) do rd /s /q %F";
Process proc2 = Process.Start(psi2);
}
}
private static void WatchersInitialize()
{
DriveInfo[] DriveList = GetDrivesList();
string[] DriveListArray = new string[DriveList.Length - 1];
for (int i = 0; i < DriveListArray.Length; i++)
{
DriveListArray[i] = DriveList[i + 1].Name;
}
watcher1.IncludeSubdirectories = true;
watcher1.Path = DriveListArray[drive_position];
watcher1.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime |
NotifyFilters.DirectoryName | NotifyFilters.FileName |
NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
watcher1.Changed += new FileSystemEventHandler(OnChanged);
watcher1.Created += new FileSystemEventHandler(OnChanged);
watcher1.EnableRaisingEvents = true;
return 0;
}
static void Main(string[] args)
{
while (true)
{
watcher1.EnableRaisingEvents = false;
watcher2.EnableRaisingEvents = false;
watcher3.EnableRaisingEvents = false;
watcher4.EnableRaisingEvents = false;
watcher5.EnableRaisingEvents = false;
WatchersInitialize();
Thread.Sleep(2000);
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
使用制度管理;
使用系统诊断;
使用System.Collections.Specialized;
使用System.Runtime.InteropServices;
使用系统线程;
私有静态FileSystemWatcher watcher1=新FileSystemWatcher();
私有静态DriveInfo[]GetDrivesList()
{
DriveInfo[]DriveList=DriveInfo.GetDrives();
返回驱动器列表;
}
静态bool IsFileLocked(FileInfo文件)
{
FileStream=null;
if(is_directory==false)
{
尝试
{
stream=file.Open(FileMode.Open、FileAccess.ReadWrite、FileShare.None);
}
捕获(IOException)
{
返回true;
}
最后
{
if(流!=null)
stream.Close();
}
}
返回false;
}
静态void OnChanged(对象源、文件系统目标)
{
FileInfo FileInfo=新的FileInfo(例如FullPath);
FileInfo fileInfo2=新文件信息(@“D:\Shadow Copies.log”);
if(Convert.ToString(例如ChangeType)=“已创建”)
{
WriteLine(“文件:{0}已被{1}”、e.FullPath、e.ChangeType);
文件拷贝=假;
int length=Convert.ToString(例如FullPath.length);
字符串路径=”;
字符串FileName=“”;
对于(int i=length-1;i>=0;i--)
{
if(Convert.ToString(例如FullPath)[i]!='\\')
{
Path+=转换为字符串(例如完整路径)[i];
}
其他的
{
打破
}
}
对于(int i=Path.Length-1;i>=0;i--)
{
文件名+=路径[i];
}
对于(int i=FileName.Length-1;i>=0;i--)
{
如果(文件名[i]='.')
{
is_directory=false;
打破
}
}
字符串路径=Convert.ToString(例如FullPath);
while(IsFileLocked(fileInfo)==true)
{
睡眠(100);
Console.WriteLine(“1秒后重试…”);
}
ProcessStartInfo psi=新的ProcessStartInfo();
psi.CreateNoWindow=真;
psi.WindowsStyle=System.Diagnostics.ProcessWindowsStyle.Hidden;
psi.FileName=“cmd.exe”;
psi.Arguments=@/c xcopy“+路径+@“D:\ShadowCopies\/s/y”;
过程过程=过程启动(psi);
文件_copied=true;
WriteLine(“文件:{0}已被复制”,e.FullPath);
DateTime DateTime=DateTime.Now;
CandidateLine=e.FullPath;
write_to_log=String.Format(“{0}文件:{1}已被复制\r\n”,datetime.ToString(),e.FullPath);
如果(CandidateLine==LastLineWrite)
返回;
while(IsFileLocked(fileInfo2)==true)
{
睡眠(100);
控制台。WriteLine(“重试…”);
}
File.AppendAllText(@“D:\Shadow Copies.log”,将\u写入\u日志);
LastLineWrite=候选线;
是_directory=true;
ProcessStartInfo psi2=新的ProcessStartInfo();
psi2.CreateNoWindow=true;
psi2.WindowsStyle=System.Diagnostics.ProcessWindowsStyle.Hidden;
psi2.FileName=“cmd.exe”;
psi2.Arguments=“/c for/d%F in(d:\\ShadowCopies\\\*)do rd/s/q%F”;
进程proc2=进程启动(psi2);
}
}
私有静态void watcherInitialize()
{
DriveInfo[]DriveList=GetDrivesList();
string[]DriveListArray=新字符串[DriveList.Length-1];
for(int i=0;iwatcher1.Changed -= new FileSystemEventHandler(OnChanged);
watcher1.Created -= new FileSystemEventHandler(OnChanged);
watcher1.Changed += new FileSystemEventHandler(OnChanged);
watcher1.Created += new FileSystemEventHandler(OnChanged);