Question

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?

Was it helpful?

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.

OTHER TIPS

Such specific functionality is not built into C#, but you could easily write it yourself, by opening a file and writing bytes (0) into it until the disk is full.

Take note some file systems will limit your max file size.

This has worked for me to get the free space of a drive (C#), via System.Management

ManagementObject di = new ManagementObject("win32_logicaldisk.deviceid=\"C:\"");
di.Get();
UInt64 freeSpace = (UInt64)di["FreeSpace"]; //in bytes

Now you can write files named via System.Guid.NewGuid() to fill up all the space (use a multiple of the filesystem's cluster size).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top