Changing Drive Letter of an Azure Drive (aka X-drive)

written on February 6, 2011

Sometimes it might be necessary that you want your Azure drive to be always mounted on a fixed drive letter. Consider a scenario of an Azure VM Role where you need to mount an azure drive for data persistance and your VM demands the same letter for you azure drive, e.q. you installed SQL Server on your VM Role and for mdf files you specified azure drive as path so as to make the data persist. But now, we know that Azure drives are mounted on random-drive letters. To always have a fixed letter what you can do is that after your drive is mounted, you can change the drive letter to a fixed value using diskpart from within the windows service you use to mount the drive in VM Role, or from other part of code if you are not working with VM Role. Check this post to know [how to mount Azure Drive in VM Role.](http://techyfreak.blogspot.com/2011/02/mounting-azure-drive-in-azure-virtual.html) To get a basic idea on how to change drive letter using diskpart visit this Microsoft support link : [http://support.microsoft.com/kb/928543](http://support.microsoft.com/kb/928543) To change the drive letter of the mounted Azure Drive using diskpart, we will create a temporary file in local resource storage. This temp file will be used to store the current and target drive letters, and using this we can construct diskpart commands. Following code can be used to achieve the same:
//create temporary diskpart file
string diskpartFile = drive.CachePath + "\\diskpart.txt";
if (File.Exists(diskpartFile))
{
File.Delete(diskpartFile);
}
string driveLetter = drive.DriveLetter;
//start the process
using (Process changeletter = new Process())
{
changeletter.StartInfo.Arguments = "/s" + " " + diskpartFile;
changeletter.StartInfo.FileName = System.Environment.GetEnvironmentVariable("WINDIR") + "\\System32\\diskpart.exe";
changeletter.Start();
changeletter.WaitForExit();
}
File.Delete(diskpartFile);