1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 |
using
System; using
System.Collections.Generic; using
System.Linq; using
System.ServiceProcess; using
System.Text; namespace
startSqlServer { class
Program { static
void
Main( string [] args) { ServiceController sc = getStatus(); if
(sc.DisplayName.ToString() == "SQL Server (MSSQLSERVER)" ) { string
status = "" ; if
(sc.Status == ServiceControllerStatus.ContinuePending) { status = "当前服务状态为 继续 " ; } if
(sc.Status == ServiceControllerStatus.Paused) { status = "当前服务状态为 暂停 " ; } if
(sc.Status == ServiceControllerStatus.PausePending) { status = "当前服务状态为 正在暂停 " ; } if
(sc.Status == ServiceControllerStatus.Running) { status = "当前服务状态为 启动 " ; } if
(sc.Status == ServiceControllerStatus.StartPending) { status = "当前服务状态为 正在 " ; } if
(sc.Status == ServiceControllerStatus.Stopped) { status = "当前服务状态为 停止 " ; } if
(sc.Status == ServiceControllerStatus.StopPending) { status = "当前服务状态为 正在停止 " ; } Console.WriteLine(status); lable: Console.WriteLine( "输入1启动服务 输入2停止服务,输入3退出" ); string
item = Console.ReadLine().Trim(); switch
(item) { case
"1" : if
(getStatus().Status == ServiceControllerStatus.Stopped || getStatus().Status == ServiceControllerStatus.StartPending) { sc.Start(); Console.WriteLine( "启动成功" ); } else { cw( "操作失败, 当前服务处于启动或正在启动状态" ); } goto
lable; case
"2" : if
(getStatus().Status != ServiceControllerStatus.Stopped && getStatus().Status != ServiceControllerStatus.StartPending) { sc.Close(); sc.Stop(); Console.WriteLine( "停止成功" ); } else { cw( "操作失败, 当前服务处于停止或正在停止状态" ); } goto
lable; case
"3" : break ; default : Console.WriteLine( "输入有误,请重新输入" ); goto
lable; } } } public
static
void
cw( string
word) { Console.WriteLine(word); } public
static
ServiceController getStatus() { ServiceController[] service = ServiceController.GetServices(); for
( int
i = 0; i < service.Length; i++) { if
(service[i].DisplayName.ToString() == "SQL Server (MSSQLSERVER)" ) { return
service[i]; } } throw
new
Exception( "未找到该服务" ); } } } |
记得要先引用using System.ServiceProcess;
原文:http://www.cnblogs.com/Rock-Lee/p/3533515.html