gpt4 book ai didi

C#如何把光驱的盘符从D : to Z:改成

转载 作者:太空狗 更新时间:2023-10-29 18:25:47 25 4
gpt4 key购买 nike

我正在尝试编写一个方法,将 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!
*****************************************************************/

关于C#如何把光驱的盘符从D : to Z:改成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5084297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com