Search code examples
c#fileshred

Writing to free space


I was wondering if It is possible to write to freespace in C#? I mean something like FreeSpace.WriteAllBytes() or like what some shredder apps do?

How can I do so?


Solution

  • If your intention is simply to overwrite all the free space available on a hard drive, you can use the GetDiskFreeSpaceEx API to determine how many bytes are available and write a file that large (or spread it out among several files).

    P/Invoke for C#:

    [DllImport("kernel32")]
    public static extern int GetDiskFreeSpaceExW(string dir, ref ulong freeBytesAvailable,
        ref ulong totalNumBytes, ref ulong totalFreeBytes);
    

    You can use a class like System.Random to fill an array of bytes with random values before writing them, if that might interest you.

    Edit: Wasn't aware of the System.IO.DriveInfo class, which could be simpler than using the mentioned API.