你可以使用 FileSystemWatcher
类来监听目录中的文件变化,并获取最新的文件。下面是一个示例代码,用于监听特定目录的变化,并在有新文件生成时获取最新的文件。
示例代码
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
public class FileWatcher
{
private FileSystemWatcher watcher;
private string directoryPath;
private PictureBox pictureBox;
public FileWatcher(string path, PictureBox pb)
{
directoryPath = path;
pictureBox = pb;
watcher = new FileSystemWatcher
{
Path = directoryPath,
Filter = "*.*", // 监听所有文件类型
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
};
watcher.Created += OnChanged;
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// 等待文件完全写入
System.Threading.Thread.Sleep(100);
// 获取最新的文件
var