Handling disk full errors when copying files in C#

By FoxLearn 11/20/2024 7:20:51 AM   28
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.

there is not enough space on the disk

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#.

Related