Hi @דני שטרית ,Welcome to Microsoft Q&A,
Normally if the drive is not ready, you cannot get it.
A simpler way is to add a try catch section to get to avoid errors.
For example:
using System;
using System.IO;
class Program
{
static void Main()
{
//Specify the drive letter of the CD-ROM drive
string driveLetter = "D"; // Change this value to the appropriate drive letter
try
{
// Construct the drive path
string drivePath = $"{driveLetter}:\\";
//Create a DriveInfo object to obtain drive information
DriveInfo driveInfo = new DriveInfo(drivePath);
// Check if the drive is ready
if (driveInfo.IsReady)
{
// Get the total remaining space of the drive (in bytes)
long totalFreeSpace = driveInfo.TotalFreeSpace;
// Convert bytes to human-readable format (e.g. KB, MB, GB)
string totalFreeSpaceFormatted = FormatBytes(totalFreeSpace);
Console.WriteLine($"The total remaining space of drive {drivePath} is: {totalFreeSpaceFormatted}");
}
else
{
Console.WriteLine($"Drive {drivePath} is not available.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
// Convert bytes to human readable format
static string FormatBytes(long bytes)
{
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int counter = 0;
decimal number = bytes;
while (Math.Round(number / 1024) >= 1)
{
number /= 1024;
counter++;
}
return $"{number:n1} {suffixes[counter]}";
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.