There is no class available in .NET which allow us to access the disk properties directly. However, there are couple of ways to find the free space and other disk drive properties.
One option is to use InteropServices to call Windows APIs directly. InteropServices allow us to call un managed code and this can be used to call the Windows API "GetDiskFreeSpaceEx". This API returns couple of disk properties including available free space, total space and total free space.
The following sample code demonstrates how to call the Windows API GetDiskFreeSpaceEx to retrieve these values.
Sample Code
Step 1: Import the namespace "System.Runtime.InteropServices" :
using System.Runtime.InteropServices;
Step 2: Declare the Win32 API using the attribute "DllImport" so that it can be called from managed code.
[DllImport("kernel32", CharSet=CharSet.Auto)] static extern int GetDiskFreeSpaceEx( string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
Step 3: Call the API from managed code (C# or VB.NET) to retrieve information about the specific disk drive.
ulong freeBytesAvailable, totalBytes, freeBytes; // Call the Win32 API to retrieve disk space information. GetDiskFreeSpaceEx ( "C:", out freeBytesAvailable, out totalBytes, out freeBytes );
System.Diagnostics.Debug.WriteLine( "Total space : " + totalBytes + " Bytes" ); System.Diagnostics.Debug.WriteLine( "Free space : " + freeBytes + " Bytes" ); System.Diagnostics.Debug.WriteLine( "Available Free space : " + freeBytesAvailable + " Bytes" );
Summary
The above sample shows how the InteropServices can be used to call Windows APIs from C# and how to retrieve the disk space information.
A better .NET way of doing this would be using the class "ManagementObjectSearcher" which is part of the "Windows Management Instrumentation (WMI)" classes provided by .NET Framework. The "System.Management" namespace in .NET provides many useful classes that can be used to access Operating System properties including disk drive properties.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|