如何想要实现插件的热加载或卸载,那么我想第一步就是实时监测插件文夹中文件的变化,以便在插件文件夹中内容发生改变后,及时做出加载或卸载的操作。System.IO.FileSystemWatcher 类为可以满足我们所需的功能。
这里我们做个简单的示例,效果如下图。
示例代码如下
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Path = System.IO.Path;
namespace WpfAppFileSystemWatcher
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
StartMonitoring(GetCurrentProgramPath() + "\\Plugins");
}
public static string GetCurrentProgramPath()
{
// 获取当前执行的程序集
var assembly = Assembly.GetEntryAssembly();
// 获取程序集所在的路径
var assemblyLocation = assembly.Location;
// 获取程序集所在的目录
var programPath = Path.GetDirectoryName(assemblyLocation);
return programPath;
}
private FileSystemWatcher _fileWatcher;
private void StartMonitoring(string directoryPath)
{
// 创建 FileSystemWatcher 实例
_fileWatcher = new FileSystemWatcher();
// 设置要监视的目录路径
_fileWatcher.Path = directoryPath;
// 设置要监视的更改类型(例如:修改、创建、删除)
_fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// 添加事件处理程序
_fileWatcher.Changed += OnChanged;
_fileWatcher.Created += OnChanged;
_fileWatcher.Deleted += OnChanged;
// 开启事件监听
_fileWatcher.EnableRaisingEvents = true;
Debug.WriteLine($"已开始监视文件夹: {directoryPath}");
}
private void OnChanged(object source, FileSystemEventArgs e)
{
Debug.WriteLine($"文件或文件夹发生变更: {e.FullPath},事件类型: {e.ChangeType}");
}
public void StopMonitoring()
{
if (_fileWatcher != null)
{
// 停止引发事件
_fileWatcher.EnableRaisingEvents = false;
// 清理资源
_fileWatcher.Dispose();
_fileWatcher = null;
Console.WriteLine("已停止监视文件夹");
}
}
}
}
本文中文件实时监测,参考了这篇文章。