C#如何将CDROM的驱动器号从D:更改为Z:

前端之家收集整理的这篇文章主要介绍了C#如何将CDROM的驱动器号从D:更改为Z:前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个将CDROM驱动器从字母D更改为字母Z并且与WMI没有任何运气的方法.有没有其他方法可以使用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();
        }
    }
}

解决方法

我不知道WMI,但是你可以用winapi更改驱动器号,这是我将一个 example(只需要你需要的部分)移植到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());
}

小心运行此代码,您必须先删除驱动器安装点,然后再将其分配给新的字母,这可能会导致问题,原始代码

/*****************************************************************
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!
*****************************************************************/
原文链接:https://www.f2er.com/csharp/243135.html

猜你在找的C#相关文章