views:

140

answers:

3

I'd like to have a go at writing something which shows the state of a hard drive in terms of how fragmented it is. Maybe even has a go at de-fragmenting it.

But I've realised that I don't fully understand how this works.

Can anyone explain this to me and perhaps offer some suggestions of where I might start?

I mainly use C# - would this be a suitable language to have a go at putting something together.

Thanks in advance

A: 

To show the fragmentation state of a filesystem, you would have to find out which blocks of the disk belong to which files. All files that do not solely consist of consecutive blocks are fragmented; they contain holes and/or the blocks are scattered over the disk.

To defragment a filesystem you would have to move around the blocks so that all files are consecutive and rewrite the metadata to have the filesystem in a consistent state in the end.

David Schmitt
A: 

When files are saved the bytes they use is put into allocated blocks, if the file grows and the next consecutive block is not available, the OS starts writing to the next available block, splitting the file into 2 fragments.

Defragmentation collects files into consecutive blocks by moving blocks out of the way (into free space) so that the file being defragmented can have consecutive blocks. for non Solid State hard drives this affects performance (as there is no seek time reading consecutive blocks)

Some defragmenters move more commonly read files to the outside of the disk (since it spins faster the further away from the spindle it is).

JamesB
+4  A: 

Please begin with the Wikipedia Article on Disk Fragmentation

Then after that, it depends on how low-level you want to go.

First for the official howto see Defragmenting Files on MSDN.

From the article....

  1. Use the FSCTL_GET_VOLUME_BITMAP control code to find a place on the volume that is large enough to accept an entire file. Note If necessary, move other files to make a place that is large enough. Ideally, there is enough unallocated clusters after the first extent of the file that you can move subsequent extents into the space after the first extent.
  2. Use the FSCTL_GET_RETRIEVAL_POINTERS control code to get a map of the current layout of the file on the disk.
  3. Walk the RETRIEVAL_POINTERS_BUFFER structure returned by FSCTL_GET_RETRIEVAL_POINTERS.
  4. Use the FSCTL_MOVE_FILE control code to move each cluster as you walk the structure. Note You may need to renew either the bitmap or the retrieval structure, or both at various times as other processes write to the disk.

For a C# wrapper of the above, check out this blog post.

Finally, depending on your situation, you can use the WMI Defrag method on the Win32_Volume class.

Hope this helps.

kervin
thanks - I hadn't realised quite how complicated the subject is.
Matt Joslin