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;
}