1. Set Up the .NET Core API
If you don’t already have an API project, create one:
dotnet new webapi -n FileWatcherApi
cd FileWatcherApi
2. Add the FileSystemWatcher Implementation
Open the project in your favorite editor (e.g., Visual Studio, VS Code).
Create a new service class to manage file watching. For example:
- Add a new folder named
Services. - Create a file named
FileWatcherService.cs.
Implement the FileWatcherService:
using System;
using System.IO;
namespace FileWatcherApi.Services
{
public class FileWatcherService
{
private readonly FileSystemWatcher _fileWatcher;
public FileWatcherService(string pathToWatch)
{
if (!Directory.Exists(pathToWatch))
{
throw new DirectoryNotFoundException($"The directory '{pathToWatch}' does not exist.");
}
_fileWatcher = new FileSystemWatcher
{
Path = pathToWatch,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime,
Filter = "*.*" // Monitor all files
};
_fileWatcher.Created += OnFileCreated;
_fileWatcher.Changed += OnFileChanged;
_fileWatcher.Deleted += OnFileDeleted;
_fileWatcher.Renamed += OnFileRenamed;
}
public void Start()
{
_fileWatcher.EnableRaisingEvents = true;
Console.WriteLine("File watcher started...");
}
public void Stop()
{
_fileWatcher.EnableRaisingEvents = false;
Console.WriteLine("File watcher stopped...");
}
private void OnFileCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File created: {e.FullPath}");
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File changed: {e.FullPath}");
}
private void OnFileDeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File deleted: {e.FullPath}");
}
private void OnFileRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"File renamed from {e.OldFullPath} to {e.FullPath}");
}
}
}
3. Register the Service in Program.cs
Update Program.cs to register and start the FileWatcherService
using FileWatcherApi.Services;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Configure the FileWatcherService
var pathToWatch = @"C:\Path\To\Watch"; // Replace with your target directory
var fileWatcherService = new FileWatcherService(pathToWatch);
fileWatcherService.Start();
// Add cleanup on shutdown
app.Lifetime.ApplicationStopping.Register(() =>
{
fileWatcherService.Stop();
});
// Map a simple endpoint to test the API
app.MapGet("/", () => "File Watcher API is running!");
app.Run();
4. Run the Application
Modify or create files in the directory specified by pathToWatch, and observe the logs in the console.
Comments
Post a Comment