How to restart service remotely?

前端 未结 3 1553
南笙
南笙 2021-02-07 10:57

I can start or stop service remotely from .net project.

ConnectionOptions options = new ConnectionOptions();
options.Username = @\"192.168.36.22\\test\";
options         


        
3条回答
  •  后悔当初
    2021-02-07 11:44

    Service controller didn't work for me, so I used Cmd to do it.

    Process.Start("CMD.exe", "/C sc \\\\remoteMachine stop \"serviceName\"&sc \\\\remoteMachine start \"serviceName\"");
    

    To overcome credentials issue, I used class from this https://stackoverflow.com/a/5433640/2179222 answer.

    So in the end It looked like this:

        private static void RestartService(string remoteMachine, string serviceName, string userName, string password)
        {
            using (new NetworkConnection($"\\\\{remoteMachine}", new NetworkCredential(userName, password)))
            {
                Process.Start("CMD.exe", $"/C sc \\\\{remoteMachine} stop \"{serviceName}\"&sc \\\\{remoteMachine} start \"{serviceName}\"");
            }
        }
    

提交回复
热议问题