Search code examples
c#fragmentationdefragmentation

How does disk de-fragmenting work?


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


Solution

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