I am trying to write a metod that will change the CDROM drive from letter D to letter Z and not having any luck with WMI. Is there some other way that I can do this using C#?
public void setVolCDROM()
{
SelectQuery queryCDROM =
new SelectQuery("SELECT * FROM Win32_cdromdrive");
ManagementObjectSearcher searcherCDROM =
new ManagementObjectSearcher(queryCDROM);
foreach(ManagementObject cdromLetter in searcherCDROM.Get())
{
MessageBox.Show(cdromLetter["Drive"].ToString() + "\n"
+ cdromLetter["Manufacturer"].ToString());
if (cdromLetter["Drive"].ToString() == "D:")
{
cdromLetter["Drive"] = "Z:";
cdromLetter.Put();
}
}
}
I don't know about WMI, but you can change the drive letter with winapi, here is an example that I ported (just the part you need) to C#
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetVolumeNameForVolumeMountPoint(string
lpszVolumeMountPoint, [Out] StringBuilder lpszVolumeName,
uint cchBufferLength);
[DllImport("kernel32.dll")]
static extern bool DeleteVolumeMountPoint(string lpszVolumeMountPoint);
[DllImport("kernel32.dll")]
static extern bool SetVolumeMountPoint(string lpszVolumeMountPoint,
string lpszVolumeName);
const int MAX_PATH = 260;
private void ChangeDriveLetter()
{
StringBuilder volume = new StringBuilder(MAX_PATH);
if (!GetVolumeNameForVolumeMountPoint(@"D:\", volume, (uint)MAX_PATH))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (!DeleteVolumeMountPoint(@"D:\"))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (!SetVolumeMountPoint(@"Z:\", volume.ToString()))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
Be careful running this code, you have to delete the drive mount point before assigning it to a new letter, this could lead to problems, from the original code:
/*****************************************************************
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
This program will change drive letter assignments, and the
changes persist through reboots. Do not remove drive letters
of your hard disks if you do not have this program on floppy
disk or you might not be able to access your hard disks again!
*****************************************************************/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With