9.16 Get the Total Free Space on a Drive


Problem

You need to examine a drive and determine how many bytes of free space are available.

Solution

Use the unmanaged Win32 API function GetDiskFreeSpaceEx , which is declared in kernel32.dll.

Discussion

None of the .NET file system classes allow you to determine the amount of free space that's available. However, this information can easily be retrieved using the Win32 API function GetDiskFreeSpaceEx , which returns the amount of used space, the amount of free space, and the amount of available free space as output arguments.

The following Console application uses this technique:

 using System; using System.Runtime.InteropServices; public class GetFreeSpace {     [DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA" )]     private static extern long GetDiskFreeSpaceEx(       string lpDirectoryName, out long lpFreeBytesAvailableToCaller,        out long lpTotalNumberOfBytes, out long lpTotalNumberOfFreeBytes);     private static void Main() {         long result, total, free, available;         result = GetDiskFreeSpaceEx("c:", out available, out total, out free);         if (result != 0) {             Console.WriteLine("Total Bytes: {0:N}", total);             Console.WriteLine("Free Bytes: {0:N}", free);             Console.WriteLine("Available Bytes: {0:N}", available);         }         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net