C# How to get the system drive of remote server

本文提供了一段使用C#编程语言通过Windows Management Instrumentation (WMI)接口获取系统驱动器路径的代码示例。通过连接到目标计算机的管理范围,执行查询并解析结果来获取Windows目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值