Due to permissions, I'm having trouble connecting to a remote server (Windows Server 2016) using c# when code is deployed on IIS. When I run it on visual studio it runs ok but on IIS I'm getting an unauthorized exception.
Stacktrace : System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Management.ManagementScope.InitializeGuts(Object o) at System.Management.ManagementScope.Initialize() at System.Management.ManagementObjectSearcher.Initialize() at System.Management.ManagementObjectSearcher.Get()
Code snippet that I used is:
ConnectionOptions connectoptions = new ConnectionOptions();
//connectoptions.Impersonation = ImpersonationLevel.Impersonate;
connectoptions.Username = username;
connectoptions.Password = password;
//IP Address of the remote machine
ManagementScope scope = new ManagementScope(@"\\" + ip + @"\root\cimv2");
scope.Options = connectoptions;
//WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection collection = searcher.Get();
Console.WriteLine("Logged in");
foreach (ManagementObject service in collection)
{
Console.WriteLine(service);
}
}