Home
Manage Your Code
Snippet: Find Next Available Drive Letter (C#)
Title: Find Next Available Drive Letter Language: C#
Description: Uses System.IO.DriveInfo to determine the next available drive letter. Views: 5861
Author: Dave Donaldson Date Added: 3/15/2007
Copy Code  
1public string FindNextAvailableDriveLetter()
2{
3    // build a string collection representing the alphabet

4    StringCollection alphabet = new StringCollection(); 
5
6    int lowerBound = Convert.ToInt16('a');
7    int upperBound = Convert.ToInt16('z');
8    for(int i = lowerBound; i < upperBound; i++)
9    {
10        char driveLetter = (char)i;
11        alphabet.Add(driveLetter.ToString());
12    }
13
14    // get all current drives

15    DriveInfo[] drives = DriveInfo.GetDrives();
16    foreach (DriveInfo drive in drives)
17    {
18        alphabet.Remove(drive.Name.Substring(0, 1).ToLower()); 
19    }
20
21    if (alphabet.Count > 0)
22    {
23        return alphabet[0];
24    }
25    else
26    {
27        throw (new ApplicationException("No drives available."));
28    }
29}