您只需调用一个方法,即 WipeFile,代码如下所示。因此,您真正需要做的就是调用 WipeFile 并提供要删除的文件的完整路径,以及您想要覆盖它的次数。
public void WipeFile(string filename, int timesToWrite)
{
try
{
if (File.Exists(filename))
{
// Set the files attributes to normal in case it's read-only.
File.SetAttributes(filename, FileAttributes.Normal);
// Calculate the total number of sectors in the file.
double sectors = Math.Ceiling(new FileInfo(filename).Length/512.0);
// Create a dummy-buffer the size of a sector.
byte[] dummyBuffer = new byte[512];
// Create a cryptographic Random Number Generator.
// This is what I use to create the garbage data.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Open a FileStream to the file.
FileStream inputStream = new FileStream(filename, FileMode.Open);
for (int currentPass = 0; currentPass < timesToWrite; currentPass++)
{
UpdatePassInfo(currentPass + 1, timesToWrite);
// Go to the beginning of the stream
inputStream.Position = 0;
// Loop all sectors
for (int sectorsWritten = 0; sectorsWritten < sectors; sectorsWritten++)
{
UpdateSectorInfo(sectorsWritten + 1, (int) sectors);
// Fill the dummy-buffer with random data
rng.GetBytes(dummyBuffer);
// Write it to the stream
inputStream.Write(dummyBuffer, 0, dummyBuffer.Length);
}
}
// Truncate the file to 0 bytes.
// This will hide the original file-length if you try to recover the file.
inputStream.SetLength(0);
// Close the stream.
inputStream.Close();
// As an extra precaution I change the dates of the file so the
// original dates are hidden if you try to recover the file.
DateTime dt = new DateTime(2037, 1, 1, 0, 0, 0);
File.SetCreationTime(filename, dt);
File.SetLastAccessTime(filename, dt);
File.SetLastWriteTime(filename, dt);
// Finally, delete the file
File.Delete(filename);
WipeDone();
}
}
catch(Exception e)
{
WipeError(e);
}
}
我添加了一些事件只是为了能够跟踪过程中发生的事情。
- PassInfoEvent - 返回正在运行的通道以及要运行的通道总数。
- SectorInfoEvent - 返回正在写入的扇区以及要写入的扇区总数。
- WipeDoneEvent - 擦除过程完成的指示器。
- WipeErrorEvent - 如果出现任何问题,则返回异常。
使用 .NET 安全删除文件