PowerToys/Plugins/Wox.Plugin.Program/FileChangeWatcher.cs

59 lines
1.8 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Wox.Infrastructure.Logger;
2016-08-20 03:34:20 +08:00
using Wox.Plugin.Program.ProgramSources;
2016-01-06 14:45:08 +08:00
namespace Wox.Plugin.Program
{
2016-07-21 07:02:13 +08:00
internal static class FileChangeWatcher
{
2016-07-21 07:02:13 +08:00
private static readonly List<string> WatchedPath = new List<string>();
2016-08-20 03:34:20 +08:00
// todo remove previous watcher events
2016-08-20 06:24:21 +08:00
public static void AddAll(List<UnregisteredPrograms> sources, string[] suffixes)
2016-08-20 03:34:20 +08:00
{
foreach (var s in sources)
{
if (Directory.Exists(s.Location))
{
AddWatch(s.Location, suffixes);
}
}
}
public static void AddWatch(string path, string[] programSuffixes, bool includingSubDirectory = true)
{
2016-07-21 07:02:13 +08:00
if (WatchedPath.Contains(path)) return;
if (!Directory.Exists(path))
{
Log.Warn($"FileChangeWatcher: {path} doesn't exist");
return;
}
2016-07-21 07:02:13 +08:00
WatchedPath.Add(path);
foreach (string fileType in programSuffixes)
{
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = path,
IncludeSubdirectories = includingSubDirectory,
2016-07-21 07:02:13 +08:00
Filter = $"*.{fileType}",
EnableRaisingEvents = true
};
watcher.Changed += FileChanged;
watcher.Created += FileChanged;
watcher.Deleted += FileChanged;
watcher.Renamed += FileChanged;
}
}
private static void FileChanged(object source, FileSystemEventArgs e)
{
2016-07-21 07:02:13 +08:00
Task.Run(() =>
{
2016-07-21 07:02:13 +08:00
Main.IndexPrograms();
});
}
}
}