Handling disk full errors when copying files in C#
By Tan Lee Published on Nov 20, 2024 232
You can use PInvoke to call the GetDiskFreeSpaceEx function from the Windows kernel to check the available disk space on both local and network drives.
This function provides detailed information about the total, free, and available space on a specified disk or network location.
How to use PInvoke to call the GetDiskFreeSpaceEx
function from the kernel32.dll
library to check whether there is enough free space on a remote network drive before copying a file.
// PInvoke to GetDiskFreeSpaceEx function from kernel32.dll [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool GetDiskFreeSpaceEx( string lpDirectoryName, out ulong lpFreeBytesAvailable, // Free space available to the current user out ulong lpTotalNumberOfBytes, // Total space on the disk out ulong lpTotalNumberOfFreeBytes); // Total free space on the disk // Method to check if there is enough space to copy the file bool HasEnoughSpace(string srcFile, string destPath) { var fileBytes = (ulong)(new FileInfo(srcFile).Length); GetDiskFreeSpaceEx(destPath, out var availableBytes, out _, out _); return fileBytes <= availableBytes; } // Example usage of the HasEnoughSpace method if (!HasEnoughSpace(@"C:\MyFile.txt", @"\\127.0.0.1\C$")) { Console.WriteLine("Not enough space available. Please clear some space."); // You can add additional code to handle the situation }
GetDiskFreeSpaceEx
is declared using the DllImport
attribute to import the unmanaged function from kernel32.dll
. This allows your C# code to call the Windows API function for disk space querying.
This solution is a good approach to handling disk full errors when copying files to both local and network locations in C#.
Categories
Popular Posts
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Portal HTML Bootstrap
Nov 13, 2024
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024
Freedash bootstrap lite
Nov 13, 2024