Saturday, May 30, 2009

Wipe file

// Wipe file

public static void Wipe(string fileName)
{
if (File.Exists(fileName))
{
File.SetAttributes(fileName, FileAttributes.Normal);
Random rnd = new Random((int)DateTime.Now.Ticks);
FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Write);
int fileLength = (int)file.Length;
int offset = 0;

const int BUFFER_SIZE = 100;
byte[][] buffers = new byte[4][];
buffers[0] = new byte[BUFFER_SIZE];
buffers[1] = new byte[BUFFER_SIZE];
buffers[2] = new byte[BUFFER_SIZE];
buffers[3] = new byte[BUFFER_SIZE];

rnd.NextBytes(buffers[0]);
rnd.NextBytes(buffers[2]);
for (int i = 0; i < BUFFER_SIZE; i++)
{
buffers[1][i] = 0;
buffers[3][i] = 0xff;
}

while (offset < (fileLength - BUFFER_SIZE))
{
for (int i = 0; i < buffers.Length; i++)
{
file.Seek(offset, SeekOrigin.Begin);
file.Write(buffers[0], 0, BUFFER_SIZE);
file.Flush();
}
offset += 100;
}

for (int i = 0; i < buffers.Length; i++)
{
file.Seek(offset, SeekOrigin.Begin);
file.Write(buffers[0], 0, fileLength - offset);
file.Flush();
}

file.Close();

file = File.Open(fileName, FileMode.Truncate, FileAccess.Write);
file.Flush();
file.Close();

File.Delete(fileName);
}
}

No comments:

Post a Comment