Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSystemWatcher does not fire when using C++ std::ofstream

Tags:

c++

c#

monitoring

I'm trying to add a log monitor to an in-house test utility for a windows service I'm working on. The service is written in C++ (win32) and the utility is in .NET (C#)

The log monitor works for many other C++ apps I've written, but not for my service.

The only main difference I can see is that the other apps use the older ::WriteFile() to output to the log, whereas in the service I'm using std::ofstream like this:

std::ofstream logFile;
logFile.open("C:\\mylog.log");
logFile << "Hello World!" << std::endl;
logFile.flush();

From my utility I use FileSystemWatcher like this:

FileSystemWatcher fsw = new FileSystemWatcher(@"C:\", "mylog.log");
fsw.Changed += new FileSystemEventHandler(fsw_Handler);
fsw.EnableRaisingEvents = true;

But for the service, it never gets any change events as the log is updated. I've found that any example code using FileSystemWatcher I've come across online has the same exact issue as well... But, I know the events should be available because other log monitor apps (like BareTail) work fine with the service log file.

I'd rather get the C# code for the utility to just work so it works with anything, but if I have to change the logging code for the service I will. Does anyone see what's going wrong here?

like image 692
Adam Haile Avatar asked Apr 22 '26 22:04

Adam Haile


2 Answers

Just a wild guess, but does the utility fire when the service actually closes the log file? The reason I ask is that Windows might not be updating the file metadata on calls to std::ofstream::flush() -- which also sometimes happens in some virtual filesystem implementations in other operating systems.

I'll also check whether the utility has the appropriate permissions to access to the log file created by the service. If you're running the service as an administrator you might have to run the utility as the same user.

like image 77
Dean Michael Avatar answered Apr 25 '26 13:04

Dean Michael


Have you tried setting

        fsw.NotifyFilter = NotifyFilters.LastWrite;

or other filters?

like image 35
AppDeveloper Avatar answered Apr 25 '26 13:04

AppDeveloper