DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Wipe File

04.24.2007
| 3349 views |
  • submit to reddit
        
        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);
            }
        }