本文基于Visual Studio 2010, .net framework选取的2.0版本为基本环境创建一个最简单的windows服务。
        
        
       
     
     
     方法/步骤
    
- 
首先打开VS2010(或者其他版本),创建Windows服务项目 
 
- 
创建完成后切换到代码视图,代码中默认有OnStart和OnStop方法执行服务开启和服务停止执行的操作,下面代码是详细解释: using System; using System.IO; usingSystem.ServiceProcess; using System.Text; usingSystem.Timers; namespaceTestService { 
 public partial class Service1 : ServiceBase { 
 public Service1() { 
 InitializeComponent(); } protected override voidOnStart(string[] args) { 
 //服务开启执行代码 StartDoSomething(); } protected override void OnStop() { 
 //服务结束执行代码 } protected override void OnPause() { 
 //服务暂停执行代码 base.OnPause(); } protected override void OnContinue() { 
 //服务恢复执行代码 base.OnContinue(); } protected override void OnShutdown() { 
 //系统即将关闭执行代码 base.OnShutdown(); } private void StartDoSomething() { 
 System.Timers.Timer timer = newSystem.Timers.Timer(10000); //间隔10秒 timer.AutoReset = true; timer.Enabled = false; //执行一次 timer.Elapsed += newElapsedEventHandler(WriteSomething); timer.Start(); } private void WriteSomething(objectsource, System.Timers.ElapsedEventArgs e) { 
 FileStream fs = null; try { 
 fs = newFileStream(“d:/1.txt”, FileMode.OpenOrCreate); string strText = @”//实例化一个文件流—>与写入文件相关联 FileStream fs = newFileStream(sf.FileName, FileMode.Create); //实例化一个StreamWriter–>与fs相关联 StreamWriter sw = newStreamWriter(fs); //开始写入 sw.Write(this.textBox1.Text); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close();”; //获得字节数组 byte[] data = newUTF8Encoding().GetBytes(strText); //开始写入 fs.Write(data, 0, data.Length); //清空缓冲区、关闭流 fs.Flush(); fs.Close(); fs.Dispose(); } catch { 
 } finally { 
 if (fs != null) { 
 fs.Close(); fs.Dispose(); } } } } } 
- 
然后切换到设计视图,右键点击下图中圈选的“添加安装程序” 
 
- 
选中下图第一个控件,点击F4,右边切换到属性视图;更改属性视图中的Account属性为LocalService(本地服务) 
- 
选中上面第二个控件,点击F4,右边切换到属性视图。更改ServiceName为你自己喜欢的服务名称,记住不要和系统的冲突了哦~,亲!StartType默认为手动,你可以更改为自动 (Automatic)或禁用(Disabled) 
- 
编译项目,然后win+R输入cmd进入命令窗口。去对应.net版本下的目录中找到InstallUtil.exe,我项目采用的是 .net 2.0,故路径为C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 
 
- 
InstallUtil.exe对应.net版本目录图,如下 
 
 END
 
 







