关于WIndows服务的介绍,之前写过一篇: http://blog.csdn.net/yysyangyangyangshan/article/details/7295739。可能这里对如何写一个服务不是很详细。现在纯用代码的形式介绍一下windows服务是如何开发和安装的。
开发环境:Win7 32位;工具:visualstudio2010。

因为win7自带的就有.net环境,算是偷一下懒吧。因为无论是手动安装或程序安装都要用到。一个目录(默认C盘为操作系统的情况):C:\Windows\Microsoft.NET\Framework,如果你的代码是.net2.0:C:\Windows\Microsoft.NET\Framework\v2.0.50727;4.0:C:\Windows\Microsoft.NET\Framework\v4.0.30319。

下面看一下代码:

一、创建windows服务

如图新建一个Windows服务



进入程序如图



空白服务如下

 public partial class Service1 : ServiceBase
{
System.Threading.Timer recordTimer; public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
} protected override void OnStop()
{
}
}

只要在OnStart里完成你的功能代码即可。本例中我们做一个定时向本地文件写记录的功能。
如图



创建一个类,用户写文件,

 public class FileOpetation
{
/// <summary>
/// 保存至本地文件
/// </summary>
/// <param name="ETMID"></param>
/// <param name="content"></param>
public static void SaveRecord(string content)
{
if (string.IsNullOrEmpty(content))
{
return;
} FileStream fileStream = null; StreamWriter streamWriter = null; try
{
string path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, string.Format("{0:yyyyMMdd}", DateTime.Now)); using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(content); if (streamWriter != null)
{
streamWriter.Close();
}
} if (fileStream != null)
{
fileStream.Close();
}
}
}
catch { }
}
}

那么在Service1中调用,

 public partial class Service1 : ServiceBase
{
System.Threading.Timer recordTimer; public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
IntialSaveRecord();
} protected override void OnStop()
{
if (recordTimer != null)
{
recordTimer.Dispose();
}
} private void IntialSaveRecord()
{
TimerCallback timerCallback = new TimerCallback(CallbackTask); AutoResetEvent autoEvent = new AutoResetEvent(false); recordTimer = new System.Threading.Timer(timerCallback, autoEvent, 10000, 60000 * 10);
} private void CallbackTask(Object stateInfo)
{
FileOpetation.SaveRecord(string.Format(@"当前记录时间:{0},状况:程序运行正常!", DateTime.Now));
}
}

这样服务算是写的差不多了,下面添加一个安装类,用于安装。
如图,在service1上右键-添加安装程序,



如图,添加一个安装程序,



如图,添加完成后,



设置相应的属性,给serviceInstaller1设置属性,主要是描述信息。如图,



给serviceProcessInstaller1设置,主要是account。一般选localsystem,如图,



这样服务已经写好了。那么如何添加到windows服务里面去呢。除了之前说过的用CMD,InstallUtil.exe和服务的exe文件进行手动添加。这些可以用代码来实现的。当然主要过程都是一样的。代码实现也是使用dos命令来完成的。

二、代码安装Windows服务

上面写好的服务,最终生成的是一个exe文件。如图,



安装程序安装时需要用到这个exe的路径,所以方便起见,将这个生成的exe文件拷贝至安装程序的运行目录下。

安装代码,

class Program
{
static void Main(string[] args)
{
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); string sysDisk = System.Environment.SystemDirectory.Substring(0,3); string dotNetPath = sysDisk + @"WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe";//因为当前用的是4.0的环境 string serviceEXEPath = Application.StartupPath+@"\MyFirstWindowsService.exe";//把服务的exe程序拷贝到了当前运行目录下,所以用此路径 string serviceInstallCommand = string.Format(@"{0} {1}", dotNetPath, serviceEXEPath);//安装服务时使用的dos命令 string serviceUninstallCommand = string.Format(@"{0} -U {1}", dotNetPath, serviceEXEPath);//卸载服务时使用的dos命令 try
{
if (File.Exists(dotNetPath))
{
string[] cmd = new string[] { serviceUninstallCommand }; string ss = Cmd(cmd); CloseProcess("cmd.exe");
} }
catch
{
} Thread.Sleep(1000); try
{
if (File.Exists(dotNetPath))
{
string[] cmd = new string[] { serviceInstallCommand }; string ss = Cmd(cmd); CloseProcess("cmd.exe");
} }
catch
{ } try
{
Thread.Sleep(3000); ServiceController sc = new ServiceController("MyFirstWindowsService"); if (sc != null && (sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
sc.Start();
}
sc.Refresh();
}
catch
{
}
} /// <summary>
/// 运行CMD命令
/// </summary>
/// <param name="cmd">命令</param>
/// <returns></returns>
public static string Cmd(string[] cmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
for (int i = 0; i < cmd.Length; i++)
{
p.StandardInput.WriteLine(cmd[i].ToString());
}
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return strRst;
} /// <summary>
/// 关闭进程
/// </summary>
/// <param name="ProcName">进程名称</param>
/// <returns></returns>
public static bool CloseProcess(string ProcName)
{
bool result = false;
System.Collections.ArrayList procList = new System.Collections.ArrayList();
string tempName = "";
int begpos;
int endpos;
foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
{
tempName = thisProc.ToString();
begpos = tempName.IndexOf("(") + 1;
endpos = tempName.IndexOf(")");
tempName = tempName.Substring(begpos, endpos - begpos);
procList.Add(tempName);
if (tempName == ProcName)
{
if (!thisProc.CloseMainWindow())
thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程
result = true;
}
}
return result;
}
}

这段代码其实可以放在项目中的某个地方,或单独执行程序中,只好设置好dotNetPath和serviceEXEPath路径就可以了。

运行完后,如图,


再在安装目录下看记录的文件,

这样,一个windows服务安装成功了。

代码下载:http://download.csdn.net/detail/yysyangyangyangshan/6032671

C#创建、安装一个Windows服务的更多相关文章

  1. 创建第一个windows服务

    windows服务应用程序是一种长期运行在操作系统后台的程序,它对于服务器环境特别适合,它没有用户界面,不会产生任何可视输出,任何用户输出都回被写进windows事件日志. 计算机启动时,服务会自动开 ...

  2. tomcat创建一个windows服务

    具体步骤如下: 1.把JDK解压到C:\Program Files\Java下,Tomcat解压到D:\tomcat下 2.配置环境变量 JAVA_HOME:C:\Program Files\Java ...

  3. 为MongoDB创建一个Windows服务

    一:选型,根据机器的操作系统类型来选择合适的版本,使用下面的命令行查询机器的操作系统版本 wmic os get osarchitecture 二:下载并安装 附上下载链接 点击安装包,我这里是把文件 ...

  4. [翻译] 使用 .NET Core 3.0 创建一个 Windows 服务

    原文: .NET Core Workers as Windows Services 在 .NET Core 3.0 中,我们引入了一种名为 Worker Service 的新型应用程序模板.此模板旨在 ...

  5. 【先定一个小目标】Redis 安装成windows服务-开机自启

    1.第一步安装成windows服务的,开机自启动 redis-server --service-install redis.windows.conf 2.启动\关闭 redis-server --se ...

  6. MongoDB 3.4 安装以 Windows 服务方式运行

    1.首先从https://www.mongodb.com/download-center#community 下载社区版,企业版也是类似. 2.双击运行安装,可自定义安装路径,这里采用默认路径(C:\ ...

  7. MongoDB安装成为Windows服务及日常使用遇到问题总结

    安装MongoDB: http://blog.csdn.net/liuzhoulong/article/details/6124566 严格按照上面的步骤,设置数据库目录,设置日志目录,安装服务.可是 ...

  8. MongoDB配置服务--MongoDB安装成为windows服务

    MongoDB安装成为windows服务 1.打开命令提示符(最好以管理员的身份打开),然后输入: mongod --logpath "D:\MongoDB\data\log\logs.tx ...

  9. 用 nssm 把 Nginx 安装成 Windows 服务方法

    总之:用 nssm 比 srvany.exe 简便多了.1. 下载nginx windows版本:http://nginx.org/ 2. 下载 nssm :http://nssm.cc/3. 安装N ...

随机推荐

  1. [JavaScript] js判断是否在微信浏览器中打开

    用JS来判断了,经过查找资料终于实现了效果, function is_weixn(){     var ua = navigator.userAgent.toLowerCase();     if(u ...

  2. 李洪强iOS开发之提交AppStory时候遇到的坑

    今天我在上传AppStore的时候,遇到了很多的问题.一直找不到问题的原因,但是最后终于发现问题的原因 ,是因为钥匙串签名无效的问题,解决方案如下: 证书签名无效解决: 1,按照你那个链接下载,htt ...

  3. cocos2d-x mac or windows eclipse android ------ Eclipse工程里面还会有许多警告

    由于公司的游戏项目比较特殊,  coco2d-x 的  ios  和  android  的游戏 代码 没有采用 共享目录的开发方式.所以android 内的 c++ 游戏代码全部放在 jni 下, ...

  4. is present but cannot be translated into a null value due to being declared as a primitive type

    解决办法:把基本类型改为对象,譬如此处将pageId的类型由int 改为Integer 2016-10-19 19:36:11.275 DEBUG [http-nio-9999-exec-2][org ...

  5. jni.h头文件详解二

    作者:左少华 博客:http://blog.csdn.net/shaohuazuo/article/details/42932813 转载请注明出处:http://blog.csdn.net/shao ...

  6. Oracle Form属性、内置子程序、触发器、系统变量简要

    一.属性 1.1 通用属性 名称(Name) 子类信息(Subclass Information) 备注(Comments) 标题(Title) 方向(Direction) 字体名称(Font Nam ...

  7. Eclipse下Properties解析(重要的可修改的会用红笔标注)

    以项目为例,打开Properties界面 显示如图: Resource(资源) 展开为 Builders Hibernate Settings Java Build Path(个人认为最重要的) Ja ...

  8. 我的第一个Struts程序

    1.程序结构 2.各种文件 LoginAction.java package com.tfj.action; public class LoginAction { private String use ...

  9. lnmp.org一键安装包

    LNMP安装快速导航:LNMP安装提示,LNMP安装教程.安装失败处理.虚拟主机管理.可选组件.LNMP文件目录说明.状态管理. 系统需求: CentOS/Debian/Ubuntu Linux系统 ...

  10. hdu4374One hundred layer (DP+单调队列)

    http://acm.hdu.edu.cn/showproblem.php?pid=4374 去年多校的题 今年才做 不知道这一年都干嘛去了.. DP的思路很好想 dp[i][j] = max(dp[ ...