How to wipe a file completely in C#

By FoxLearn 11/5/2024 1:58:12 PM   106
To securely wipe a file in C# according to the HMG IS5 Baseline, you need to follow a procedure that goes beyond simple file deletion.

To ensure a file is completely erased and unrecoverable, various secure wiping standards are used, including (British HMG IS5, Russian GOST, US Army AR380-19, German VSITR, etc)

HMG IS5 is a data destruction standard used by the British government. The HMG IS5 Baseline method securely wipes data by overwriting a file with 0s. The more advanced HMG IS5 Enhanced method involves three passes: first overwriting with 0s, then with 1s, and finally with randomly generated bytes to ensure complete data destruction.

Here is a sample code for implementing the HMG IS5 Baseline method, which securely wipes a file by overwriting it with 0s

class HMGIS5
{
    public static void WipeFile(string filePath)
    {
        using (var fs = File.OpenWrite(filePath))
        {
            // Make 0s
            var bytes = Enumerable.Repeat<byte>(0x00, (int)fs.Length).ToArray(); 
            // Write 0s to file
            fs.Write(bytes, 0, bytes.Length);
        } 
        // And delete the file
        File.Delete(filePath);
    }
}

By using this approach, you are adhering to secure file wiping practices, which is in line with HMG IS5 guidelines.