开发者

Writing to free space

I was wondering if It is possib开发者_JAVA技巧le to write to freespace in C#? I mean something like FreeSpace.WriteAllBytes() or like what some shredder apps do?

How can I do so?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜