所以我有一个同步程序,我正在使用filesystemwatcher来监视目录中的更改。现在我有一个列表框,我会在Changed,Created,Renamed和Deleted中添加不同的文本。现在我注意到的是,有时当我创建一个文件时,它会给我文字:
“文件已创建”
“文件已更改”
我在某处读到了不应该使用filesystemwatcher导致事件被触发的时候有时它不应该被触发。
现在我遇到了这个问题(我认为这是因为一次有多个事件),当我在我正在观看的目录中拖动文件时,它应该将文件复制到第二个目录。如果它已存在于第二个目录中,则应删除它然后复制它。现在我收到了错误:
The process cannot access the file because it is being used by another process
在我删除第二个目录中的现有文件的行。 现在我想知道Filesystemwatcher是否存在问题。因为它也会触发事件,也许它仍在被“改变”。这不应该被触发。
我的问题是:
filesystemwatcher是问题吗?(更像是,这是一个已知的问题吗?)
如果是这样的话:
有什么东西可以替换filewatcher吗?
如果没有,这是我的代码+一些变量的解释:
Source =第一个目录
target =第二个目录
记录(); =执行readquery
的PostgreSQL(); =使用strSelectCmd在postgressql中插入(与它无关)
public static void copyfolder()
{
String source = ConfigurationManager.AppSettings[@"Directory1"];
String target = ConfigurationManager.AppSettings[@"Directory2"];
Copy(@source, @target);
}
(string.IsNullOrEmpty(filename)== false)执行检查数据库中是否存在该文件。
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
logger("File created> " + e.FullPath + " -Date:" + DateTime.Now);
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
strSelectCmd = "INSERT INTO" + tablepostgresql + " (" + column1 + "," + column2 + "," + column3 + "," + column4 + ") VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
readquery = "select * from " + tablemysql + " where name='" + name + "'";
postgresql();
Record();
if (string.IsNullOrEmpty(filename) == false)
{
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(30)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target, Path.ChangeExtension(source, Path.GetExtension(source)));
if (File.Exists(copy_file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, copy_file);
}
else // The file failed to become available within 10 seconds.
{
logger("Copy has failed reason: File is being used by another program");
}
}
}
if (demo == "yes")
{
query = "INSERT INTO " + tablemysql + " (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
Mysql();
}
}
}
错误出现在此行:
File.Delete(copy_file);