code:
[DllImport("advapi32.DLL", SetLastError = true)]
publicstaticexternint LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, refIntPtr phToken);
staticstring UserName = "Administrator";
staticstring Password = "#***********";
staticstring Domin = "DOMIN";
staticstring Computer = "COMPUTERNAME OR IPADDRESS";
staticvoid Main(string[] args)
{
Console.WriteLine(GetSysDrive());
}
staticstring GetSysDrive()
{
string sysdrive = null;
ConnectionOptions options = newConnectionOptions();
options.Username = UserName;
options.Password = Password;
ManagementScope scope = newManagementScope(@"\\"+Computer+@"\root\cimv2", options);
try
{
scope.Connect();
ObjectQuery query = newObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = newManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
sysdrive = m["WindowsDirectory"].ToString().Split(':')[0];
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsImpersonationContext wic = null;
try
{
IntPtr admin_token = newIntPtr();
if (LogonUser(UserName, Domin, Password, 9, 0, ref admin_token) != 0)
{
using (wic = newWindowsIdentity(admin_token).Impersonate())
{
for(char c='A';c<='Z';c++)
{
if (Directory.Exists(@"\\"+ Computer + @"\" + c.ToString() + @"$\Windows"))
{
sysdrive = c.ToString();
break;
}
}
}
}
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
}
return sysdrive;
}
本文提供了一段使用C#编程语言通过Windows Management Instrumentation (WMI)接口获取系统驱动器路径的代码示例。通过连接到目标计算机的管理范围,执行查询并解析结果来获取Windows目录。
746

被折叠的 条评论
为什么被折叠?



