Search code examples
c#windowsfilesizentfsfileinfo

Currently used data file growth is not reflected by FileInfo.Length


I need to get the size of a database file ideally without opening it. In fact I need to launch an event when the file changes. It is a DataFlex DAT file, quite obsolete database application. The file is being open and used by the database application and FileInfo reports the size incorrectly.

Probably the reason is described here: https://blogs.msdn.microsoft.com/oldnewthing/20111226-00/?p=8813

I am using this C# construct:

private FileInfo _dbFileInfo = new FileInfo("...");
...

_dbFileInfo.Refresh();
var len = _dbFileInfo.Length;

But the _dbFileInfo.Length does not change when the file grows. Is there any workaround for this problem without actually examining the file content?


Solution

  • I have changed the lines

    _dbFileInfo.Refresh();
    var len = _dbFileInfo.Length;
    

    to

    long len;
    using (FileStream fs = File.Open(_dbFileInfo.FullName, 
                                     FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
         len = fs.Length;
         fs.Close();
    }
    

    And now it works. Though not sure if it is the best approach.