简体   繁体   中英

How to fix InvalidOperationException in C#?

I have an application in which PC's(other and own) are added as servers using the IP address and status is set to 'Running'. An entry is created in the DB for the same.

Suppose I have added 2 servers 10.51.1.159 and 10.51.1.136, on refresh the status for 10.51.1.159 is "Running" (because it is local) and status for 10.51.1.136 is "Error" (because it is remote). When I try to debug, the following exception is thrown for 10.51.1.136.

The remote server throws an exception InvalidOperationException System.InvalidOperationException: Cannot open notifyservice service on computer '10.51.1.136'. ---> System.ComponentModel.Win32Exception: Access is denied System.InvalidOperationException: Cannot open notifyservice service on computer '10.51.1.136'. ---> System.ComponentModel.Win32Exception: Access is denied .

The code that does this is as follows:

static public void GetServerStatus(DataTable dt, string service)
{
    GetServerStatusColumns(dt);

    // get the service status for each server in the datatable
    ServiceController control = new ServiceController();
    foreach (DataRow row in dt.Rows)
    {
        try 
        {
            control.ServiceName = service;
            control.MachineName = row["SERVER_ADDRESS"].ToString();
            string status = control.Status.ToString(); // This is not set for 10.51.1.136, jumped to catch block after this.
            row["SERVICE_STATUS_ID"] = Convert.ToInt32(Enum.Format(control.Status.GetType(), control.Status, "d")) - 1;
            row["SERVICE_STATUS"] = status;

            if (status == "Running")
            {
                row["SERVICE_CANSTART"] = false;
                row["SERVICE_CANSTOP"] = true;
            } 
            else 
            {
                row["SERVICE_CANSTART"] = true;
                row["SERVICE_CANSTOP"] = false;
            }
        }
        catch (InvalidOperationException exp)
        {
            row["SERVICE_STATUS_ID"] =  5; // stopped
            row["SERVICE_STATUS"] = "Error";
            string excep = Convert.ToString(exp);
            row["SERVICE_CANSTART"] = false;
            row["SERVICE_CANSTOP"] = false;
        }
    }
}

I checked if firewall is blocking, but it doesn't seem that firewall is the problem. Kindly help me. Thanks in advance.

"Access is denied" means that the account that your application is running under do not have permission to administer the service on the other computer?

Are you running on a local account? Then change to a domain account (which got permissions on the other server).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM