C# – “Access is denied” Exception with WMI

cwmi

I am working on WMI. I want to access remote system information. The following code is working for loopback or on local host but when I try to access the remote machine it shows the following exception error:

Access is denied. (Exception from HRESULT:0X8005(E_ACCESSDENIED))

When switch is used between 2 systems.

and

The RPC server Is unavailable. (Exception from HRESULT: 0x800706BA)

When both the systems are directly connected.


OS on both systems: Windows Service Pack 2.
Firewalls = blocked.
Remote procedure service = running.

Tool : .NET Visual Studio 2008 C#

Code:

try
{
    ConnectionOptions _Options = new ConnectionOptions();
    ManagementPath _Path = new ManagementPath(s);

    ManagementScope _Scope = new ManagementScope(_Path, _Options);
    _Scope.Connect();
    ManagementObjectSearcher srcd = new ManagementObjectSearcher("select * from Win32_DisplayConfiguration");
    foreach (ManagementObject obj in srcd.Get())
    {
        //listBox5.Items.Add(obj.Properties.ToString());
        foreach (PropertyData aProperty in obj.Properties)
        {
            listBox1.Items.Add(aProperty.Name.ToString() + " : " + aProperty.Value);
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Best Answer

Note:If you do not specify credentials, the credentials of the running user will be used and so these have to be valid to access the remote computer and usually, this account has to be an admin on the remote box (not for all objects, but just to be sure).

If you are logged in with a domain account, which is valid on both computers, it would work out-of-the-box.

If you are not in a domain environment, just specify credentials.

Try this:

ConnectionOptions co = new ConnectionOptions();
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.Packet;
co.Timeout = new TimeSpan(0, 0, 30);
co.EnablePrivileges = true;
co.Username = "\\";
co.Password = "";

ManagementPath mp = new ManagementPath();
mp.NamespacePath = @"\root\cimv2";
mp.Server = "";               ///Regard this!!!!

ManagementScope ms = new ManagementScope(mp, co);
ms.Connect();

ManagementObjectSearcher srcd;
srcd = new ManagementObjectSearcher  
(
    ms, new ObjectQuery("select * from Win32_DisplayConfiguration")
);

This is working all the time for me.

From my point of view, the problem occurs, because you are not specifying a remote computer in your ManagementPath. A ManagementPath, created with the defaults, always points to the local machine. And if you just specify credentials to the local computer, this is not allowed and always fails.

br--mabra