Avalible System Drive Leters

  • Thread starter Thread starter Noah Coad [MCP & MVP]
  • Start date Start date
N

Noah Coad [MCP & MVP]

How does on determain what the avalible system drive letters are (ex: C:,
D:, etc) in C#? Thanks!

-Noah Coad
Microsoft MVP & MCP
 
You could use Environment.GetLogicalDrives. This returns you in an array of
strings the drives that are currently in use.

Another solution will be to use the Win32 API as follow:

[ DllImport( "Kernel32.dll", SetLastError=true )]
internal static extern int GetLogicalDrives();

private string GetFirstAvailableDrive()
{
// Get a mask representing drive currently in use bit0: is drive a:
int nDriveMask = GetLogicalDrives();

if (nDriveMask == 0)
{
// We had an error
throw new Exception("Unable to get list of drives that are currently
in use. Err is: " +
new Win32Exception().Message);
}

// get the first available drive (Starting from D: drive)
int nPos = 4; // Position on C: drive to start
for (int i = 3; i <= 25; i++)
{
nPos = nPos << 1; // Shift by one
if ((nDriveMask & nPos) == 0)
return (((char)(i + 65)).ToString());
}

// No device available
return null;
}
 
Back
Top