views:

73

answers:

1

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).

+3  A: 

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.

Hans Passant
Agreed - if this really is a problem, just get a SSD. Problem solved.
Mark Ransom
@nobugz, i thank you for your POV, but please allow me to explain: 1. when oftenly increasing a FileStream's size, it tends to cause fragmentation (in my experience, also see http://stackoverflow.com/questions/917309/how-can-i-limit-file-fragmentation-while-working-with-net). 2. creating a new stream of a certain size and copying the original stream into it tends to overcome the fragmentation, as the new file is allocated with a pretty sequence of clusters, so i do have a way to "fix" this.
M.A. Hanin
3. i'm not assuming fragmentation, i'm assuming it is possible, and i'm looking for a way to negate or verify my suspicions at runtime. 4. I could go the very ugly way of activating the defragAnalysis and checking the log file... but that is really ugly.5. I can tell you for sure, my customers do not defrag their disks, and most still use WinXP.@Mark Ransom, I'd love to get an SSD, and I'd love to get one for each of my clients. Maybe ten years from now, file fragmentation would be obsolete. Meanwhile...
M.A. Hanin
@nobugz, in the end, you are probably right, this is probably premature optimization. Still, i'd love to get a answer to the question itself (disregarding the motivation)
M.A. Hanin
I'd recommend you ask a different question: "How can I detect the degree of fragmentation in Windows", never mentioning managed code.
Hans Passant