这是我用来挂载ISO的代码
// With help of WMICodeCreator
ManagementObject mo = new ManagementObject("root\\Microsoft\\Windows\\Storage",
"MSFT_DiskImage.ImagePath='" + isoFile + "',StorageType=1",
null);
// Obtain in-parameters for the method
ManagementBaseObject inParams = mo.GetMethodParameters("Mount");
// Execute the method and obtain the return values.
ManagementBaseObject outParams = mo.InvokeMethod("Mount", inParams, null);outParams只是作为文档这里返回一个bool。
如果我发出这个命令:
mo.Get();
string device = mo.GetPropertyValue("DevicePath");..。设备字符串显示\\.\CDROM0。它显示了这个值,即使我挂载了第二个ISO。
发布于 2022-04-26 02:10:26
我在Jim MountISO.wmi on GitHub创建的一个C++项目中找到了一个解决方案。
这里是我的最后一个C#类,用于自动安装和卸载8+中的iso映像,并检索自动安装的驱动器号。与典型的PowerShell方法相比,它速度更快,可靠性更高。
using System.Management;
using System.Threading;
namespace IsoTools
{
public static class IsoMounter
{
private const string WmiScope = @"root\Microsoft\Windows\Storage";
/// <summary>Mounts an ISO disc image file.</summary>
/// <param name="isoPath">
/// The full path of the ISO to be mounted.
/// </param>
/// <returns>
/// A System.Char representing a drive volume letter.
/// </returns>
public static char Mount(string isoPath)
{
string isoObjectPath = BuildIsoObjectPath(isoPath);
using (var isoObject =
new ManagementObject(WmiScope, isoObjectPath, null))
{
using (ManagementBaseObject inParams =
isoObject.GetMethodParameters("Mount"))
{
isoObject.InvokeMethod("Mount", inParams, null);
}
}
// The query used to retrieve the volume letter for an image.
string volumeQuery = "ASSOCIATORS OF {" + isoObjectPath + "}" +
"WHERE AssocClass = MSFT_DiskImageToVolume " +
"ResultClass = MSFT_Volume";
char mountLetter = '\0';
using (var query =
new ManagementObjectSearcher(WmiScope, volumeQuery))
{
// Run query until drive is mounted
while (mountLetter < 65)
{
Thread.Sleep(50);
using (ManagementObjectCollection queryCollection =
query.Get())
{
foreach (ManagementBaseObject item in queryCollection)
{
mountLetter = item["DriveLetter"].ToString()[0];
}
}
}
}
return mountLetter;
}
/// <summary>Dismount an ISO disc image file.</summary>
/// <param name="isoPath">
/// The full path of the ISO to be mounted.
/// </param>
public static void Dismount(string isoPath)
{
using (var isoObject = new ManagementObject(
WmiScope,
BuildIsoObjectPath(isoPath),
null))
{
using (ManagementBaseObject inParams =
isoObject.GetMethodParameters("Dismount"))
{
isoObject.InvokeMethod("Dismount", inParams, null);
}
}
}
/// <summary>Creates the WMI pathstring for an ISO image.</summary>
/// <param name="isoPath">
/// The full path of the ISO to be mounted.
/// </param>
/// <returns>A System.String representing a WMI pathstring.</returns>
private static string BuildIsoObjectPath(string isoPath)
{
// Single quoted paths do not allow escaping of single quotes
// within the ImagePath. Use double quotes and escape backslashes.
return "MSFT_DiskImage.ImagePath=\"" +
isoPath.Replace("\\", "\\\\") +
"\",StorageType=1";
}
}
}https://stackoverflow.com/questions/70513795
复制相似问题