.netfilesystemslow-levelfragmentationdefragmentation

Programmatically determine a file's fragmentation status


Is it possible to determine a specific file's fragmentation status (that is, the amount of distinct fragments this file occupies)? If so, how can this be done using .net?

The motivation is this: my application is keeping data in a FileStream, changing its size on-demand. This eventually causes the file to be fragmented. I'd like to monitor the file's fragmentation status, and based upon that - make a decision if the file should be copied and replaced by a new file (thus "defragmenting" it without making changes to the MFT).


Solution

  • This squarely falls in the "premature optimization" category. It is not at all guaranteed that you'll cause fragmentation, the disc may well have uncommitted clusters past the file end and often does. Perhaps more the point, there isn't anything in the .NET framework that allows you to detect or fix this. Accessing the volume's MFT requires unmanaged code and admin privileges.

    Defragging a disk is a normal machine maintenance task. It became automatic with Win7.