我正在编写一个程序,它使用 FileSystemWatcher 来监视给定目录的更改,当它收到 OnCreated 或 OnChanged 事件时,它会将那些已创建/更改的文件复制到指定目录。起初我遇到了 OnChanged/OnCreated 事件可以发送两次的问题(如果它需要处理 500MB 文件是 Not Acceptable )但是我想出了一个办法解决这个问题并且我真正被阻止的是得到以下 IOException: 该进程无法访问文件“C:\Where are Photos\bookmarks (11).html”,因为它正被另一个进程使用。
因此,防止程序复制它应该复制的所有文件。 所以正如我提到的,当用户使用这个程序时,他/她指定了监视目录,当用户复制/创建/更改该目录中的文件时,程序应该获得 OnCreated/OnChanged 事件,然后将该文件复制到其他几个目录。 在所有情况下都会发生上述错误,如果用户复制的文件很少需要覆盖被监视文件夹中的其他文件,或者复制多个文件的批量,甚至有时复制受监视目录中的一个文件时。 整个程序很大,所以我将发送最重要的部分。 创建时:
private void OnCreated(object source, FileSystemEventArgs e) {
AddLogEntry(e.FullPath, "created", "");
// Update last access data if it's file so the same file doesn't
// get processed twice because of sending another event.
if (fileType(e.FullPath) == 2) {
lastPath = e.FullPath;
lastTime = DateTime.Now;
}
// serves no purpose now, it will be remove soon
string fileName = GetFileName(e.FullPath);
// copies file from source to few other directories
Copy(e.FullPath, fileName);
Console.WriteLine("OnCreated: " + e.FullPath);
}
OnChanged:
private void OnChanged(object source, FileSystemEventArgs e) {
// is it directory
if (fileType(e.FullPath) == 1)
return; // don't mind directory changes itself
// Only if enough time has passed or if it's some other file
// because two events can be generated
int timeDiff = ((TimeSpan)(DateTime.Now - lastTime)).Seconds;
if ((timeDiff < minSecsDiff) && (e.FullPath.Equals(lastPath))) {
Console.WriteLine("-- skipped -- {0}, timediff: {1}", e.FullPath, timeDiff);
return;
}
// Update last access data for above to work
lastPath = e.FullPath;
lastTime = DateTime.Now;
// Only if size is changed, the rest will handle other handlers
if (e.ChangeType == WatcherChangeTypes.Changed) {
AddLogEntry(e.FullPath, "changed", "");
string fileName = GetFileName(e.FullPath);
Copy(e.FullPath, fileName);
Console.WriteLine("OnChanged: " + e.FullPath);
}
}
文件类型:
private int fileType(string path) {
if (Directory.Exists(path))
return 1; // directory
else if (File.Exists(path))
return 2; // file
else
return 0;
}
复制:
private void Copy(string srcPath, string fileName) {
foreach (string dstDirectoy in paths) {
string eventType = "copied";
string error = "noerror";
string path = "";
string dirPortion = "";
// in case directory needs to be made
if (srcPath.Length > fsw.Path.Length) {
path = srcPath.Substring(fsw.Path.Length,
srcPath.Length - fsw.Path.Length);
int pos = path.LastIndexOf('\\');
if (pos != -1)
dirPortion = path.Substring(0, pos);
}
if (fileType(srcPath) == 1) {
try {
Directory.CreateDirectory(dstDirectoy + path);
//Directory.CreateDirectory(dstDirectoy + fileName);
eventType = "created";
} catch (IOException e) {
eventType = "error";
error = e.Message;
}
} else {
try {
if (!overwriteFile && File.Exists(dstDirectoy + path))
continue;
// create new dir anyway even if it exists just to be sure
Directory.CreateDirectory(dstDirectoy + dirPortion);
// copy file from where event occured to all specified directories
using (FileStream fsin = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
using (FileStream fsout = new FileStream(dstDirectoy + path, FileMode.Create, FileAccess.Write)) {
byte[] buffer = new byte[32768];
int bytesRead = -1;
while ((bytesRead = fsin.Read(buffer, 0, buffer.Length)) > 0)
fsout.Write(buffer, 0, bytesRead);
}
}
} catch (Exception e) {
if ((e is IOException) && (overwriteFile == false)) {
eventType = "skipped";
} else {
eventType = "error";
error = e.Message;
// attempt to find and kill the process locking the file.
// failed, miserably
System.Diagnostics.Process tool = new System.Diagnostics.Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = "\"" + srcPath + "\"";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern)) {
System.Diagnostics.Process.GetProcessById(int.Parse(match.Value)).Kill();
}
Console.WriteLine("ERROR: {0}: [ {1} ]", e.Message, srcPath);
}
}
}
AddLogEntry(dstDirectoy + path, eventType, error);
}
}
我检查了我程序中的所有地方,每当我使用一些文件时,我都会在 using block 中使用它,所以甚至将事件写入日志(我省略的类,因为可能已经有太多代码在帖子中) 不会锁定文件,这是不应该的,因为所有操作都使用 using 语句 block 。
如果不是我的程序通过 Windows 或其他方式从用户“复制”进程,我根本不知道谁在锁定文件。
现在我有两个可能的“解决方案”(我不能说它们是干净的解决方案,因为它们是 hack,因此不可取)。由于问题可能出在 fileType 方法上(还有什么可以锁定文件?)我尝试将其更改为此,以模拟“阻塞直到准备好打开”操作:
文件类型:
private int fileType(string path) {
FileStream fs = null;
int ret = 0;
bool run = true;
if (Directory.Exists(path))
ret = 1;
else {
while (run) {
try {
fs = new FileStream(path, FileMode.Open);
ret = 2;
run = false;
} catch (IOException) {
} finally {
if (fs != null) {
fs.Close();
fs.Dispose();
}
}
}
}
return ret;
}
这是尽我所能告诉(测试),但是......它是 hack,更不用说其他缺陷了。
我可以尝试的另一个“解决方案”(我还没有测试)是在 fileType() 方法末尾的某处使用 GC.Collect() .可能比前一个更糟糕的“解决方案”。
有人能告诉我,到底是什么东西锁定了文件,阻止它打开,我该如何解决?我错过了什么?
提前致谢。
请您参考如下方法:
问题很可能是在您已经尝试访问文件时仍在复制文件。这尤其可能发生在大文件上。
您可以在实际开始处理之前尝试检查文件是否可以用写权限打开。有关如何执行此操作的详细信息,请查看 here .
如果您可以影响创建文件的过程,那么可能会有更好的解决方案。先复制临时扩展名的文件,复制完成后重命名,触发FileSystemWatcher事件。
