动态修改Windows Service名称

View Code
 11)创建文件:ServiceConfig.txt
 2 
 32)写如下配置:
 4 
 5 ServiceName=DaemonTask1
 63)写一个配置类:
 7 
 8 public class Config
 9     {
10         public static string GetServiceConfig(string key)
11         {
12             string[] result = { string.Empty };
13             string fileName1 = "ServiceConfig.txt";
14             string fileName2 = "..\\..\\ServiceConfig.txt";
15             string fileName = string.Empty;
16 
17 
18             if (File.Exists(fileName1))
19             {
20                 fileName = fileName1;
21             }
22             else if (File.Exists(fileName2))
23             {
24                 fileName = fileName2;
25             }
26 
27 
28             if (string.IsNullOrEmpty(fileName))
29             {
30                 return string.Empty;
31             }
32             else
33             {
34                 result = File.ReadAllLines(fileName, Encoding.Default);
35                 if (result == null || result.Length == 0)
36                 {
37                     return string.Empty;
38                 }
39 
40 
41                 foreach (string item in result)
42                 {
43                     string[] pair = item.Split('=');
44                     if (pair[0].Equals(key))
45                     {
46                         return pair[1];
47                     }
48                 }
49             }
50 
51 
52             return string.Empty;
53         }
54     }
554)在ProjectInstaller的构造函数中增加一行:
56 
57         public ProjectInstaller()
58         {
59             InitializeComponent();
60 
61             serviceInstaller1.ServiceName = Config.GetServiceConfig("ServiceName");
62         }
635)在Service1的构造函数中增加一行:
64 
65         public Service1()
66         {
67             InitializeComponent();
68 
69 
70             ServiceName = Config.GetServiceConfig("ServiceName");
71         }
72 
73 大功告成!

 

posted on 2012-05-07 18:00  哥是技术人  阅读(448)  评论(0)    收藏  举报

导航