// Writes zeros to a file stream, with space advantage on compressed and sparse files. public static void WriteZeros(System.IO.FileStream fs, long begin, long end) { #if NETSTANDARD2_0 if (fs.Length < end) { fs.SetLength(end); // Just extend the length of the file } #else // Hopefully this works as expected, it's hard to get this working right over the .NET framework fs.Flush(); // So that ALL of the buffers are cleared and written to the file. zeroinfo zi = new zeroinfo(); int retd; // Get the file handle IntPtr hndl = fs.SafeFileHandle.DangerousGetHandle(); if (end > fs.Length) { while (end > fs.Length) { long pos = fs.Length; long write = Math.Min(0x100000, end - pos); fs.SetLength(pos + write); zi.begin = pos; zi.end = pos + write; SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero); } } zi.begin = begin; zi.end = end; SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero); fs.Position = end; #endif }
private static extern bool SetZeroData(IntPtr hDevice, uint dwControlCode, ref zeroinfo zi, int i16, IntPtr zero1, int zero, out int bytesretd, IntPtr zero2);