How to fix "COMException: A required privilege is not held by the client" error in C#?

0

I'm working on remote computer control by WMI using C#. I can connect after I have made the necessary settings on the remote computer. There is no problem so far. But when I shut down a remote computer with the Win32ShutDown command, after reboot the remote computer I received the following error:

System.Runtime.InteropServices.COMException (0x80070522): A required privilege is not held by the client. (Exception from HRESULT: 0x80070522).

How can I solve this?

My connection function:

    public static ManagementScope Connect(string ip, string userName = "", string password = "")
    {
        ManagementScope scope = null;
        try
        {
            ConnectionOptions opts;
            scope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", ip.Trim()));

            if (!string.IsNullOrEmpty(userName))
            {
                opts = new ConnectionOptions
                {
                    Username = userName,
                    Password = password,
                    EnablePrivileges = true,
                    Impersonation = ImpersonationLevel.Impersonate
                };
                scope.Options = opts;
            }
            scope.Connect(); //Error is thrown here
            return scope;
        }
        catch (Exception ex)
        {
            scope = null;
            throw ex;
        }
    }

My shutdown function:

    static void ShutDown()
    {
        try
        {
            ConnectionOptions options = new ConnectionOptions
            {
                Username = "Administrator",
                Password = "123",
                EnablePrivileges = true,
                Impersonation = ImpersonationLevel.Impersonate                     
            };
            ManagementScope scope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", "192.168.1.50", options));
            scope.Connect(); //Error is thrown here

            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem") { Scope = scope };
            mcWin32.Get();

            ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
            mboShutdownParams["Flags"] = 5;

            ManagementBaseObject mboShutdown = null;
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            Console.ReadLine();
        }
     }
c#
wmi
asked on Stack Overflow Jun 29, 2019 by Aykut Demirci • edited Jun 29, 2019 by MickyD

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0