使用C#访问Windows 7引导配置数据

本文关键字:配置 置数据 访问 Windows 使用 | 更新日期: 2023-09-27 18:25:04

我需要能够使用c#从引导配置数据存储访问当前正在运行的Windows安装的标识符GUID。它可以从运行以下命令行返回:

bcdedit /enum {current} /v

我的问题是,在c#中,如果我尝试直接运行此命令(即使程序以管理员身份运行),我会被告知bcdedit不存在。我正在使用:

ProcessStartInfo procStartInfo = new ProcessStartInfo("bcdedit.exe", "/enum {current} /v");

我研究过的另一件事是使用WMI,但我唯一的参考是http://msdn.microsoft.com/en-us/library/windows/desktop/aa362673(v=vs.85).aspx,这不是很有帮助。

最好的解决方案是,如果我不必使用bcdedit,而是可以使用本机WMI类。如何使用C#找到当前的Windows引导加载程序标识符?

使用C#访问Windows 7引导配置数据

直接访问bcdedit.exe似乎有很多问题,但我能够弄清楚如何在C#中使用WMI访问BcdStore:

ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
connectionOptions.EnablePrivileges = true;
// The ManagementScope is used to access the WMI info as Administrator
ManagementScope managementScope = new ManagementScope(@"root'WMI", connectionOptions);
// {9dea862c-5cdd-4e70-acc1-f32b344d4795} is the GUID of the System BcdStore
ManagementObject privateLateBoundObject = new ManagementObject(managementScope, new ManagementPath("root''WMI:BcdObject.Id='"{9dea862c-5cdd-4e70-acc1-f32b344d4795}'",StoreFilePath='"'""), null);
ManagementBaseObject inParams = null;
inParams = privateLateBoundObject.GetMethodParameters("GetElement");
// 0x24000001 is a BCD constant: BcdBootMgrObjectList_DisplayOrder
inParams["Type"] = ((UInt32)0x24000001);
ManagementBaseObject outParams = privateLateBoundObject.InvokeMethod("GetElement", inParams, null);
ManagementBaseObject mboOut = ((ManagementBaseObject)(outParams.Properties["Element"].Value));
string[] osIdList = (string[]) mboOut.GetPropertyValue("Ids");
// Each osGuid is the GUID of one Boot Manager in the BcdStore
foreach (string osGuid in osIdList)
{
    ManagementObject currentManObj = new ManagementObject(managementScope, new ManagementPath("root''WMI:BcdObject.Id='"" + osGuid + "'",StoreFilePath='"'""), null);
            MessageBox.Show("" + currentManObj.GetPropertyValue("Id"));
}

这将获取BcdStore中每个Windows启动管理器的GUID,并将其显示在MessageBox中。需要注意的是,您必须具有正确的ConnectionOptions,并且此程序必须以管理员身份运行。

感谢Ross Johnston的项目:http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=18233找到BCD常数,并为Tran Dinh Hop的项目在:http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=19208它拥有所有与BcdStore一起工作的C#代码(除了前面提到的常量)。

更新:

使用:

ManagementObject privateLateBoundObject = new ManagementObject(managementScope, new ManagementPath("root''WMI:BcdObject.Id='"{fa926493-6f1c-4193-a414-58f0b2456d1e}'",StoreFilePath='"'""), null);

将获取当前正在运行的Windows引导管理器的BcdObject。如果您随后致电:

currentManObj.GetPropertyValue("Id")

您将获得当前运行的Windows引导管理器的GUID,该GUID不同于"{fa926493-6f1c-4193-a414-58f0b2456d1e}",后者是指向当前引导管理器。

感谢Microsoft Scripting Guy.aspx及其项目:http://technet.Microsoft.com/en-us/magazine/2008.07.heyscriptingguy.aspx?pr=拥有链接到当前引导管理器的GUID常量的博客。

请注意,%systemroot%''system32中只有一个64位bcdedit.exe。如果你的应用程序是32位的,它将无法启动64位bcdedit,因为WOW64层将system32''目录重新映射到syswow64。最好使用WMI接口。