简体   繁体   中英

C# FileSystemWatcher file size is only updating with windows explorer

I've a problem with the FileSystemWatcher in C#. I watch a file used by another program. This is not a problem. The problem is that the only value that changes with the file is the size. The other program is writing the file without updating the change or write date. And the size value is only updating when the (windows 7) explorer refreshing (F5, or clicked on the file).

FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Changed);
fileWatcher.Path = Path.GetDirectoryName(path); // get directory of file path.
fileWatcher.Filter = Path.GetFileName(path); // only this file
fileWatcher.NotifyFilter = NotifyFilter.Size; // and maybe other
fileWatcher.EnableRaisingEvents = true;

private void fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
    // ...
}

I guess that this problem can only be solved by polling. Because the file should be triggered for refreshing file info data. But I hope for another solution without polling.

About my application: Reading a file which is in use of another program. Getting the text of the file is possible with FileStream FileShare.ReadWrite. It's working fine. I want to update the textbox (reading the file) when the file has been changed. But the only value who is updating while the other program is accessing to it, is the file size. But only when the explorer is refreshing or I'm clicking on the file. This is the issue of this question. If the problem is unsolvable, the alternative is: updating the file content (reading file) all x time. (polling) without a file watcher.

Perhaps, following would solve your problem, and avoid polling. Try using WMI , querying root\\cimv2 namespace with something like:

select filesize from 'cim_datafile' where name='_your_path_'

Might differ slightly when applied from C# but along those lines. Regarding WMI, there's lots of tutorials how to initialize a WMI listener in .NET. Search around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM