How to use file watcher in WebAPI?
*I want check folder empty or not
*Not empty means the excel sheet in folder to inserted into database
How to use file watcher in WebAPI?
*I want check folder empty or not
*Not empty means the excel sheet in folder to inserted into database
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pasang TamangRank #449 · 5.6K reputationPosted Jan 11, 2023, 6:07 AM EST
Hi Sujay,
Personally I won't recommend to use Filewatcher in WebAPI project. When there is no active request on WebAPI then app pool will go to idle and in that case Filewatcher will not work. What you can do is either create a console application and run it through windows scheduler or you can create separate windows service. For me I solved the problem by using web scheduler HangFire. Every 5 minutes Hangfire check my folder if there is file or not. You can read detail about HangFire integration here https://code-maze.com/hangfire-with-asp-net-core/
Regards,
Pasang
Amit MohantyRank #112 · 20K reputationPosted Jan 11, 2023, 5:29 AM EST
If you want to check folder is empty or not, you can use this.
private static bool IsFolderEmpty(string path) { return !Directory.EnumerateFileSystemEntries(path).Any(); }string path = @"D:\Publish"; if (IsFolderEmpty(path)) Console.WriteLine($"Folder : {path} is empty"); else Console.WriteLine($"Folder : {path} is not empty");If you want to do this using FileSystemWatcher
public class FileWatcherController : ApiController { private FileSystemWatcher watcher; public FileWatcherController() { // Set the directory to watch string path = @"C:\temp\"; watcher = new FileSystemWatcher(); watcher.Path = path; // Set the filter to only pick up changes to all files watcher.Filter = "*.*"; // Enable raising events watcher.EnableRaisingEvents = true; // Add event handlers watcher.Changed += OnChanged; watcher.Created += OnChanged; watcher.Deleted += OnChanged; } private void OnChanged(object source, FileSystemEventArgs e) { // check if folder is empty or not if (IsFolderEmpty(watcher.Path)) { Console.WriteLine($"Folder : {watcher.Path} is empty"); } else { Console.WriteLine($"Folder : {watcher.Path} is not empty"); } } private bool IsFolderEmpty(string path) { return !Directory.EnumerateFileSystemEntries(path).Any(); } }