Reputation: 3696
I'm trying to follow this tutorial: https://www.youtube.com/watch?v=6lVormV8cb8
But my FileSystemWatcher events don't appear to firing. Any idea why?
ps. My knowledge of C# and the Windows API is very primitive - please take that into account with any responses.
Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
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 System.IO;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
string watchedFolder = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures");
FileSystemWatcher fsw = new FileSystemWatcher(watchedFolder);
MainWindow.Title = "Monitoring: " + fsw.Path;
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.EnableRaisingEvents = true;
}
void fsw_Changed(object sender, FileSystemEventArgs e)
{
updatedImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate ()
{
ImageSourceConverter isc = new ImageSourceConverter();
updatedImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);
}
)
);
}
}
}
Window1.xaml
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="350" Width="525"
Name="MainWindow">
<Grid>
<Image Name="updatedImage" />
</Grid>
</Window>
Upvotes: 1
Views: 187
Reputation: 216253
It seems that your XAML is missing of a critical piece.
The binding of the MainWindow_Loaded event handler.
No code is binded to that event, thus no FileSystemWatcher is created, and initialized.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="350" Width="525"
Name="MainWindow"
Loaded="MainWindow_Loaded">
Upvotes: 1