tags:

views:

116

answers:

3

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?

+3  A: 

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 system will limit your max file size

Alon
+1. It is possible (albeit tricky) to access the raw volume from within C#, but even then it's hard to zero out free space because what constitutes 'free' space can change while you're writing to it, as files get created, deleted, resized, etc.Assuming you're not limited by a quota or maximum file size limitation, creating a big file is the way to go.Don't create a bunch of small files though. Below a certain size file data lives inside the MFT record in the NTFS file system, plus it's harder to avoid serious fragmentation.
anelson
+1  A: 

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.

Siege
+1  A: 

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

Vinko Vrsalovic
Don't create alot of small files. If they're too small they'll end up stored in the MFT record and not actually given a cluster of their own. Unless their size is an integer multiple of the file system's cluster size, you won't actually overwrite all of the space in the volume. If you incrementally grow a large file by the cluster size you'll eventually fill all free space.
anelson
@anelson: Corrected, thanks.
Vinko Vrsalovic