foxygit / digitalskrivare_merge Log in
commits tags

/src/Remiss.Core/Security/SecureFile.cs · 1.2 KB

raw
namespace Remiss.Core.Security;

/// <summary>
/// Bäst-möjliga radering av filer som innehållit patientdata: skriv över
/// innehållet en gång och radera. Inte forensiskt vattentätt på SSD/kopiering,
/// men höjer ribban och håller filerna ur "återställ borttaget"-listor.
/// </summary>
public static class SecureFile
{
    public static void Shred(string path)
    {
        try
        {
            if (!File.Exists(path))
                return;

            var length = new FileInfo(path).Length;
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None))
            {
                var buffer = new byte[81920];
                long written = 0;
                while (written < length)
                {
                    var chunk = (int)Math.Min(buffer.Length, length - written);
                    fs.Write(buffer, 0, chunk);
                    written += chunk;
                }
                fs.Flush(flushToDisk: true);
            }

            File.Delete(path);
        }
        catch
        {
            // Sista utväg: se till att filen åtminstone försvinner.
            try { File.Delete(path); } catch { /* ignore */ }
        }
    }
}