C# 执行CMD 命令 远程关机

时间:2022-09-02 23:34:40
 void shutdown()        {            Process commandProcess = new Process();       
    
 try            {               
     commandProcess.StartInfo.FileName = "cmd.exe";            
     commandProcess.StartInfo.UseShellExecute = false;           
     commandProcess.StartInfo.CreateNoWindow = true;         
     commandProcess.StartInfo.RedirectStandardError = true;        
     commandProcess.StartInfo.RedirectStandardInput = true;         
     commandProcess.StartInfo.RedirectStandardOutput = true;        
     commandProcess.Start();        
     commandProcess.StandardInput.WriteLine("shutdown /r /m 127.0.0.1 /t 200 /f");      
     commandProcess.StandardInput.WriteLine("exit");     
 
           for ( !commandProcess.HasExited; )//等待cmd命令运行完毕                {     
               System.Threading.Thread.Sleep(1);                }                //错误输出     
          string tmpout = commandProcess.StandardError.ReadToEnd();      
          string tmpout1 = commandProcess.StandardOutput.ReadToEnd();      
 
      }      
        catch (Exception e)            {           
         MessageBox.Show(e.Message);         
   }         
         finally            {          
      if (commandProcess != null)  {         
           commandProcess.Dispose();        
            commandProcess = null;        
        }       
     }   
 
     }