FileSystemWatcher not working in Desktop Bridge app

Heiko 1,291 Reputation points
2023-03-24T16:10:02.8+00:00

I have a WPF app that uses FileSystemWatcher for various directories to react to changes in the directories.

For example:

"C:\ProgramData\Microsoft\Windows\Start Menu"

"C:\Users\Egon\AppData\Roaming\Microsoft\Windows\Start Menu"

As long as I start the app directly as a WPF desktop app, I get all the events when there is a change in both directories.

However, if I add a package project to the solution and launch the app as a desktop bridge app via the package project, I only get events for the general Start Menu directory, but no more events for the Start Menu directory for the user. This is reproducible on Windows 10 (VS2017) and Windows 11 (VS2022) both with .NETFramework 4.8.

Why is this and what can I do?

public MainWindow()
{
	InitializeComponent();

	string[] dirs = new string[] {
				"C:\\ProgramData\\Microsoft\\Windows\\Start Menu",
				"C:\\Users\\Egon\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu" };

	FileSystemWatcher watcher;

	foreach (string path in dirs)
	{
		if (!Directory.Exists(path))
		{
			textBox.Text += "\r\nNot found: " + path;
			continue;
		}
		watcher = new FileSystemWatcher(path);
		watcher.IncludeSubdirectories = true;
		watcher.Filter = "";
		watcher.NotifyFilter = /* NotifyFilters.Attributes | */ NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName |
								/* NotifyFilters.LastAccess | */ NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
		watcher.Changed += Watcher_Changed;
		watcher.Created += Watcher_Created;
		watcher.Deleted += Watcher_Deleted;
		watcher.Error += Watcher_Error;
		watcher.Renamed += Watcher_Renamed;
		watcher.EnableRaisingEvents = true;
		textBox.Text += "\r\nStarted: " + path;
	}
}

private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
	Watcher_OnEvent("Renamed in " + (sender as FileSystemWatcher).Path);
}

private void Watcher_Error(object sender, ErrorEventArgs e)
{
	Watcher_OnEvent("Error in " + (sender as FileSystemWatcher).Path);
}

private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
	Watcher_OnEvent("Deleted in " + (sender as FileSystemWatcher).Path);
}

private void Watcher_Created(object sender, FileSystemEventArgs e)
{
	Watcher_OnEvent("Created in " + (sender as FileSystemWatcher).Path);
}

private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
	Watcher_OnEvent("Changed in " + (sender as FileSystemWatcher).Path);
}

private void Watcher_OnEvent(string msg)
{
	Action	action = () => textBox.Text += "\r\n" + msg;

	Dispatcher.BeginInvoke(action);
}

Developer technologies Windows Presentation Foundation
Developer technologies C++
Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.