In C#, if you ever need to retrieve the total free space available on a drive, you can quickly achieve this using the DriveInfo
class from the System.IO
namespace.
Here's a snippet of code that demonstrates how to accomplish this:
using System;
using System.IO;
class Program
{
static void Main()
{
string driveLetter = "C"; // Specify the drive letter you want to check
DriveInfo drive = new DriveInfo(driveLetter);
long totalFreeSpace = drive.TotalFreeSpace;
Console.WriteLine("Total Free Space on Drive {0}: {1} bytes", driveLetter, totalFreeSpace);
}
}
In this example, we start by declaring the driveLetter
variable to specify the drive for which we want to retrieve the free space. Replace the "C" with the desired drive letter.
Next, we create a new instance of the DriveInfo
class, passing the driveLetter
as a parameter. This initializes the drive
object, which now represents the specified drive.
By accessing the TotalFreeSpace
property of the drive
object, we can retrieve the total free space available on the specified drive in bytes. You can use different properties like AvailableFreeSpace
, TotalSize
, etc., based on your specific requirements.
Finally, we print out the result using Console.WriteLine
to display the total free space in bytes.
Remember to import the System.IO
namespace to be able to use the DriveInfo
class.
Top comments (0)