c# 创建window 服务

第一步:

打开vs2008,文件->新建->项目。

ws1

 

项目类型中中选择 visual C#根目录下的windows子目录,在右侧模板中找到“windows服务”选项,并选中。

ws2

 

创建好项目后会出来一个设计界面,界面上并有一句提示语句:“若要在类中添加组件,请从工具箱中拖出它们,然后使用“属性”窗口来设置它们的属性。若要为类创建方法和事件,请单击此处切换到代码视图。”,如下图

点击设计界面中提示语“单击此处切换到代码视图”,转到后台编码界面,编写业务代码。后台页面会自动生成三个方法。方法一:构造函数,用来初始化组件。方法二:OnStart(string[] args){}启动服务时调用的方法。启动服务的时候可以进行传参。方法三:OnStop(){}方法,停止服务时调用。

贴出来具体代码,供大家参考:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Data.SqlClient;

namespace WS
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
//是否有参数
if (args.Length > 0)
{
//生成xml
CreateXML(args[0], args[1]);
//停止服务
this.Stop();
}
else
{
FileStreamWriteFile(“({\”item\”:\”没给有windows服务传参数。参数1:用户id,参数2:文件路径。\”})”, “D:\\error.txt”);
EventLog.WriteEntry(“没给有windows服务传参数。参数1:用户id,参数2:文件路径。”);
}
}

protected override void OnStop()
{

}
#region 写xml
/// <summary>
/// 创建xml
/// </summary>
/// <param name=”uid”>用户id</param>
/// <param name=”path”>路径</param>
public void CreateXML(string uid, string filepath)
{
//去掉路径中的xml文件地址
string path = filepath.Replace(“\\” + uid + “.xml”, “”);
//获取数据
DataTable dt = GetLiveSong(uid);
//是否有数据
if (dt != null && dt.Rows.Count > 0)
{
//如果不存在这个地址,则创建相关目录
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}

//生成xml信息
string xmlstr = “<?xml version=\”1.0\” encoding=\”utf-8\”?>”;
xmlstr += “<UserFMList>”;
foreach (DataRow dr in dt.Rows)
{
xmlstr += “<UserFM>”;
xmlstr += “<song_url><![CDATA[" + dr["wma"].ToString() + “]]></song_url>”;
xmlstr += “<song><![CDATA[" + dr["musicname"].ToString() + “]]></song>”;
xmlstr += “<album><![CDATA[" + dr["zjname"].ToString() + “]]></album>”;
xmlstr += “<album_id><![CDATA[" + dr["zhuanjiid"].ToString() + “]]></album_id>”;
xmlstr += “<cover><![CDATA[" + dr["pic1"].ToString() + “]]></cover>”;
xmlstr += “<song_id><![CDATA[" + dr["id"].ToString() + “]]></song_id>”;
xmlstr += “<artist><![CDATA[" + dr["singer"].ToString() + “]]></artist>”;
xmlstr += “<artist_id><![CDATA[" + dr["nclassid"].ToString() + “]]></artist_id>”;
xmlstr += “<kuan><![CDATA[300]]></kuan>”;
xmlstr += “<gao><![CDATA[300]]></gao>”;
xmlstr += “</UserFM>”;
}
xmlstr += “</UserFMList>”;
//生成xml文件
FileCreate(path + “\\” + uid + “.xml”, xmlstr);
//释放datatable资源
dt.Dispose();
}
else
{
string strpath = path.Replace(uid + “.xml”, “error.txt”);
FileStreamWriteFile(“({\”item\”:\”没有获取到歌曲.当前时间:”+new DateTime().ToLongTimeString()+”\”})”, strpath);
EventLog.WriteEntry(“({\”item\”:\”没有获取到歌曲\”})”);
}

}
private void CreateTxt(string uid,string path)
{
//获取数据
DataTable dt = GetLiveSong(uid);
//是否有数据
if (dt != null && dt.Rows.Count > 0)
{
string res = “({\”items\”:[";
foreach (DataRow dr in dt.Rows)
{
res = res + "{\"song_url\":\"" + dr["wma"].ToString() + “\”,”;
res = res + “\”song\”:\”" + dr["musicname"].ToString() + “\”,”;
res = res + “\”album\”:\”" + dr["zjname"].ToString() + “\”,”;
res = res + “\”album_id\”:\”" + dr["zhuanjiid"].ToString() + “\”,”;
res = res + “\”cover\”:\”http://www.9ku.com” + dr["pic1"].ToString() + “\”,”;
res = res + “\”song_id\”:\”" + dr["id"].ToString() + “\”,”;
res = res + “\”artist\”:\”" + dr["singer"].ToString() + “\”,”;
res = res + “\”artist_id\”:\”" + dr["nclassid"].ToString() + “\”,”;
res = res + “\”kuan\”:\”300\”,”;
res = res + “\”gao\”:\”300\”},”;
}
//去掉最后的逗号
res = res.Substring(0, res.Length – 1);
res = res + “]})”;
dt.Dispose();
FileStreamWriteFile(res, path);
}
else
{
FileStreamWriteFile(“({\”item\”:\”没有获取到歌曲\”})”, path);
EventLog.WriteEntry(“({\”item\”:\”没有获取到歌曲\”})”);
}
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name=”FileName”>文件名称</param>
/// <param name=”FileContent”>文件内容</param>
private static void FileCreate(string FileName, string FileContent)
{
FileInfo fi = new FileInfo(FileName);
if (!fi.Directory.Exists) Directory.CreateDirectory(fi.DirectoryName);

StreamWriter sw = new StreamWriter(FileName, false, Encoding.UTF8);

sw.Write(FileContent);
sw.Close();
sw.Dispose();
}
/// <summary>
/// 用FileStream写文件
/// </summary>
/// <param name=”str”></param>
/// <returns></returns>
public void FileStreamWriteFile(string str, string path)
{
byte[] byData;
char[] charData;
try
{

FileStream nFile = new FileStream(path, FileMode.Create);

//获得字符数组
charData = str.ToCharArray();
//初始化字节数组
byData = new UTF8Encoding().GetBytes(charData);
//锁定
//nFile.Lock(0, byData.Length);
//将字符数组转换为正确的字节格式
nFile.Seek(0, SeekOrigin.Begin);
nFile.Write(byData, 0, byData.Length);
//解锁
//nFile.Unlock(0, byData.Length);
nFile.Flush();
nFile.Dispose();
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.ToString());
throw ex;
}
}

/// <summary>
/// 区分表,通过用户id,区分数据在哪一张表
/// </summary>
/// <param name=”userid”>用户id</param>
/// <returns>表名</returns>
string DistinctionTable(string userid)
{
return userid.Substring(userid.Length – 1, 1);
}

/// <summary>
/// 获取喜欢的歌曲
/// </summary>
/// <param name=”uid”>用户id</param>
/// <returns>喜欢歌曲列表</returns>
public DataTable GetLiveSong(string uid)
{
//添加参数
SqlParameter[] para =
{
SqlHelper.MakeInParam(“@uid”,uid)
};

return SqlHelper.ExecuteDataTable(SqlHelper.ConnStringJkUser, CommandType.StoredProcedure, “proc_userfm”, para);

}
#endregion
}
}

ws4

第二部:添加安装程序

当业务代码编写完毕后,就要添加安装程序来进行安装服务。

打开service.cs设计页面,右键选择:添加安装程序  ,如下图

ws5

这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件 ServiceProcessInstaller 和 ServiceInstaller,并且服务的属性值被复制到组件。

若要确定如何启动服务,请单击 ServiceInstaller 组件并将 StartType 属性设置为适当的值。

  • Manual      服务安装后,必须手动启动。
  • Automatic    每次计算机重新启动时,服务都会自动启动。
  •  Disabled     服务无法启动。

将serviceProcessInstaller类的Account属性改为 LocalSystem。这样,不论是以哪个用户登录的系统,服务总会启动。

第三步:生成服务程序

通过从生成菜单中选择生成来生成项目。

注意   不要通过按 F5 键来运行项目——不能以这种方式运行服务项目。

第四步:安装服务

安装服务要通过.NET Framework中的InstallUtil.exe来进行注册和卸载。

注册程序路径:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

我们可以写一个bat文件来注册和卸载windows服务。

新建一个 注册.bat文件。格式如下:

————————————注册.bat说明———————–

注册程序路径  服务exe路径

pause关键字是注册的时候可以停留在dos界面,不会自动关闭。

—————————————————————————-

————————————–注册.bat内容—————-

C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe  ”D:\WS\bin\Debug\WS.exe”

pause

——————————————————-

服务卸载InstallUtil.exe后加-u就可以了

————————————–卸载.bat内容—————-

C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe  -u  ”D:\WS\bin\Debug\WS.exe”

pause

——————————————————-

windows服务配置文件格式:

如果你服务中有用到调用数据库或则需要用到配置文件的地方,则配置文件格式要掌握。配置文件要和.exe文件在同一目录下,并且文件名的格式为 服务.exe.config,如下图:













一、准备条件:安装好的VS2010

二、创建window service项目,取项目名为WinService_Test

三、在新建好的项目中,找到Service1.cs,右击-->View Code(查看源代码)。在源代码中,OnStart方法是在服务启动时执行的,可以在这里编写服务要执行的业务逻辑代码;OnStop方法是在服务停止时执行的,一般在这里编写终止服务线程或停止业务逻辑的代码等。

 

四、添加服务安装程序ProjectInstaller。

1、在Service1.cs的设计界面(可双击Service1.cs进入此界面),右击-->Add Installer(添加安装程序);

2、完成第一步,默认项目添加了ProjectInstaller.cs程序;

3、双击编辑文件ProjectInstaller.Designer.cs,更改下面代码:

1)在InitializeComponent方法中,添加代码

  this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

2)在InitializeComponent方法中,修改this.serviceInstaller1.ServiceName为服务类的名称,默认为Service1,如果项目的服务类的名称更改了,注意一定要修改这个值,如:服务类的名称更为WinServiceTest后,对应修改代码如下:

  this.serviceInstaller1.ServiceName = "WinServiceTest";    //服务类的名称

  this.serviceInstaller1.DisplayName = "WinServiceTest";    //安装后,在window服务管理里显示的名称

  this.serviceInstaller1.Description = "Window测试服务!";   //安装后,在window服务管理里显示的描述

 

五、添加window service安装的批处理命令

1)在项目添加一个文本文件,更名为install.bat,编辑文件的内容如下:

  %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WinService_Test.exe
  Net Start Service1

2)在项目添加一个文本文件,更名为uninstall.bat,编辑文件的内容如下:

  Net Start Service1
  %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u WinService_Test.exe

 

补充说明:

 

  • 上面黄色字体为项目的名称,也就是生成后的文件名称;红色字体为服务的名称,也就是服务类的名称。
  • 另外,文件install.bat的属性里“Copy to Output Directory”默认为“Do not copy”,编译后,在debug的文件夹里找不到install.bat的,要更改为“Copy always”或者“Copy if newer”才能出现的。uninstall.bat也跟install.bat一样的。

 

六、实际安装。

1)编译成功后,在debug文件夹中,双击install.bat完成安装;

2)安装成功后,在window的服务里,可看到此服务,如没更改服务类的名称,这里可看到服务Service1;

3)双击uninstall.bat可卸载此服务。

 

 

总结,通过上面六个步骤,实现window服务从创建到安装、卸载整个过程。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C# 添加 Windows 服务,你需要使用 System.ServiceProcess 命名空间的 ServiceBase 。下面是一个简单的示例,演示如何创建一个 Windows 服务,并将其安装到计算机上: 首先,创建一个新的 C# 项目并添加一个新的文件。在文件,定义一个,继承自 ServiceBase ,并重写 OnStart 和 OnStop 方法: ```csharp using System.ServiceProcess; namespace MyService { public partial class MyService : ServiceBase { public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { // 在此处启动服务 } protected override void OnStop() { // 在此处停止服务 } } } ``` 在 OnStart 方法,写下你想要在服务启动时执行的代码。在 OnStop 方法,写下你想要在服务停止时执行的代码。 然后,打开项目属性,选择“应用程序”选项卡,并将输出型设置为“Windows 应用程序”。这将使项目生成为可安装的 Windows 服务。 接下来,你需要编写一些代码来安装和卸载服务。可以使用 System.Configuration.Install 命名空间的 InstallUtil 工具来执行这些操作。在项目添加一个新的安装程序,如下所示: ```csharp using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; [RunInstaller(true)] public class MyServiceInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public MyServiceInstaller() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); // 设置服务的名称和显示名称 serviceInstaller.ServiceName = "MyService"; serviceInstaller.DisplayName = "My Service"; // 设置服务的启动型为自动 serviceInstaller.StartType = ServiceStartMode.Automatic; // 将服务安装程序和进程安装程序添加到安装程序集合 Installers.Add(serviceInstaller); Installers.Add(processInstaller); } } ``` 在这个,你需要设置服务的名称、显示名称和启动型。在 Installers 集合添加 ServiceInstaller 和 ServiceProcessInstaller 对象,以便安装程序可以正确地安装和卸载服务。 最后,在 Visual Studio 打开“命令提示符”窗口,并导航到项目的输出目录。运行以下命令安装服务: ```bat installutil MyService.exe ``` 运行以下命令卸载服务: ```bat installutil /u MyService.exe ``` 这些命令将使用 InstallUtil 工具来安装和卸载服务。注意,需要使用管理员权限运行命令提示符窗口,才能正确执行这些命令。 希望这个简单的示例可以帮助你开始编写自己的 Windows 服务

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值