I am creating an application that will watch for file changes in a directory although while files with an extension are detected, folders are not.
using System;
using System.IO;
using System.Diagnostics;
namespace fileSystemWatcherTest
{
class myClass
{
static void Main()
{
using var watcher = new FileSystemWatcher(@"C:\Users\Username\Desktop\Watching folder");
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.FileName
| NotifyFilters.LastWrite;
watcher.Changed = onChanged;
watcher.Created = onCreated;
watcher.Error = one rror;
watcher.Filter = "";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static void onChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return;
}
Console.WriteLine($"Changed: {e.FullPath}");
string fileExtension = Path.GetExtension(e.FullPath);
if (fileExtension != string.Empty)
{
Console.WriteLine(fileExtension);
}
}
private static void onCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"Created: {e.FullPath}");
}
private static void one rror(object sender, ErrorEventArgs e)
{
printException(e.GetException());
}
private static void printException(Exception ex)
{
if (ex != null)
{
Console.WriteLine("ERROR");
Console.WriteLine($"Message: {ex.Message}");
Console.WriteLine($"StackTrace:");
Console.WriteLine(ex.StackTrace);
Console.WriteLine("");
printException(ex.InnerException);
}
}
}
}
According to the documentation and the intellisense directories should be detected.
I believe that the problem is with the Filter property but i can't get it to work so i would appreciate some help.
CodePudding user response:
To detect directories as well, you need to add NotifyFilters.DirectoryName
to watcher.NotifyFilter
:
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastWrite;
Checkout the documentation of NotifyFilters
.