December 15, 2010

IsDrivefree

A simple helper to check if a specified drive letter is free for use:
public static class DriveInfoExtender
{
    public static bool IsDriveFree(string drive)
    {
        if (string.IsNullOrEmpty(drive) || !char.IsLetter(drive[0]))
            return false;
        if (drive.Length >= 2)
            drive = drive.Substring(0,1).ToUpper();
        bool isFree = true;
        DriveInfo[] nonFreeDrives = System.IO.DriveInfo.GetDrives();
        foreach (DriveInfo di in nonFreeDrives)
        {
            if (di.Name.StartsWith(drive))
            {
                isFree = false;
                break;
            }
        }
        return isFree;
    }
}