日期:2014-05-19  浏览次数:21021 次

c#怎么启动和停止windows服务
怎么用c#启动一个windows服务,比如说alerter,   Server之类的
谢谢!

------解决方案--------------------
调用CMD命令,Net /stop Net /start
------解决方案--------------------
类似这样的(下面是实现Ping的一个类,得到它的Ping time):

//*********************************************************************************************************
//
// Revision log:
// Date Initials Description
// 2007/02/12 joe.guo Ping command
//
// Copyright (c) 2006 Flex-Logic Limited. All Rights Reserved.
//*********************************************************************************************************
using System;
using System.Diagnostics;

namespace FLogic.Workflow.Utility.SystemMonitor {

/// <summary>
/// Ping object
/// </summary>
public class PingObject {

/// <summary>
/// Ping command
/// </summary>
/// <param name= "strIp "> a Ip address or domain name, (like: "127.0.0.1 " or "www.sohu.com " and computer name </param>
/// <returns> pingtime or other status info. </returns>
public static string CmdPing(string strIp) {
try {
Process p = new Process();

// call cmd.exe
p.StartInfo.FileName = "cmd.exe ";

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.RedirectStandardError = true;

// not display window
p.StartInfo.CreateNoWindow = true;

p.Start();

p.StandardInput.WriteLine ( "ping -n 1 "+strIp);

p.StandardInput.WriteLine( "exit ");

string strRst = p.StandardOutput.ReadToEnd();

string pingrst;
int averageLocation = strRst.IndexOf( "Average = ");
// get ping time
if(averageLocation !=-1) {
int endLocation = strRst.IndexOf( '\r ',averageLocation);
pingrst = strRst.Substring(averageLocation + 10,endLocation - averageLocation - 10);

// timeout
} else if(strRst.IndexOf( "(100% loss) ")!=-1) {
pingrst = "Timeout ";

// Destination host unreachable
} else if( strRst.IndexOf( "Destination host unreachable. ")!=-1) {
pingrst = "Destination host unreachable ";

// Unknown host
} else if(strRst.IndexOf( "Unknown host ")!=-1) {
pingrst = "Unknown host ";

// others
} else {
pingrst = strRst;

}

p.Close();

return pingrst;

} catch (Exception ex) {
throw(new Exception( "Ping " + strIp + " occur error ",ex));
}
}

}

}
------解决方案--------------------
下面的示例使用 ServiceController 类检查 Telnet 服务的当前状态。如果该服务已停止,此示例将启动该服务。如果该服务正在运行,此示例将停止该服务。

// Toggle the Telnet service -
// If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController( "Telnet ");
Console.WriteLine( "The Telnet service status is currently set to {0} ",
sc.Status.ToString());

if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))