我创建了一个小的winforms应用程序来监视某个文件夹中的新pdf文件,如果在particulair文件夹中创建了一个新的pdf文件,它会将其复制到另一个位置。
我遇到的问题是filesystemwatcher在我的列表框中创建了两个/多个条目,我该如何解决?
namespace Scanmonitor
{
public partial class Form1 : Form
{
FileSystemWatcher watcher = new FileSystemWatcher();
DateTime lastRead = DateTime.MinValue;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FileWatch();
}
public void FileWatch()
{
watcher.Path = @"C:\Scanner";
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
watcher.Filter = "*.pdf";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
public void OnChanged(object source, FileSystemEventArgs e)
{
scannerListBox.Items.Add(e.FullPath);
scannerListBox.SelectedIndex = scannerListBox.Items.Count - 1;
FileMove(scannerListBox.SelectedItem.ToString());
}
public void FileMove(string filePath)
{
try
{
System.IO.File.Copy(filePath, @"\\share\Data\Scans op OCE 600\" + Path.GetFileName(filePath));
}
catch (Exception ex)
{
ToolLabel.Text = ex.Message.ToString();
}
}
}
}
}
搞定了。
public void OnChanged(object source, FileSystemEventArgs e)
{
try
{
watcher.EnableRaisingEvents = false;
FileInfo objFileInfo = new FileInfo(e.FullPath);
if (!objFileInfo.Exists) return;
System.Threading.Thread.Sleep(5000);
FileInfo fileinformatie = new FileInfo(e.FullPath);
string strCreateTime = fileinformatie.CreationTime.ToString();
string strCreateDate = fileinformatie.CreationTime.ToString();
strCreateTime = strCreateTime.Remove(strCreateTime.LastIndexOf(" "));
strCreateDate = strCreateDate.Remove(0,strCreateDate.LastIndexOf(" "));
ProcessAllFiles(e.FullPath, strCreateTime, strCreateDate);
}
catch (Exception ex)
{
ToolLabel.Text = ex.Message.ToString();
}
finally
{
watcher.EnableRaisingEvents = true;
}
}
答案 0 :(得分:2)
您需要跟踪FileSystemWatcher已经引发事件的文件(在集合或字典中)。根据{{3}}
通用文件系统操作可能会引发多个事件。例如,当文件从一个目录移动到另一个目录时,可能会引发几个OnChanged和一些OnCreated和OnDeleted事件。移动文件是一项复杂的操作,由多个简单操作组成,因此可以引发多个事件。同样,某些应用程序(例如,防病毒软件)可能会导致FileSystemWatcher检测到其他文件系统事件。
答案 1 :(得分:0)
public void OnChanged(object source, FileSystemEventArgs e)
{
try
{
watcher.EnableRaisingEvents = false;
FileInfo objFileInfo = new FileInfo(e.FullPath);
if (!objFileInfo.Exists) return;
System.Threading.Thread.Sleep(5000);
FileInfo fileinformatie = new FileInfo(e.FullPath);
string strCreateTime = fileinformatie.CreationTime.ToString();
string strCreateDate = fileinformatie.CreationTime.ToString();
//Ignore this, only for my file information.
strCreateTime = strCreateTime.Remove(strCreateTime.LastIndexOf(" "));
strCreateDate = strCreateDate.Remove(0,strCreateDate.LastIndexOf(" "));
ProcessAllFiles(e.FullPath, strCreateTime, strCreateDate);
}
catch (Exception ex)
{
ToolLabel.Text = ex.Message.ToString();
}
finally
{
watcher.EnableRaisingEvents = true;
}
}