標籤:winform style blog http os io ar for 檔案
1.首先開啟VS2010(或者其他版本),建立Windows服務項目
2.建立完成後切換到程式碼檢視,代碼中預設有OnStart和OnStop方法執行服務開啟和服務停止執行的操作,下面代碼是詳細解釋:
注意選擇的是系統時間,不是winform中的時間。
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; //執行一次,true時沒10S執行一次。
timer.Elapsed += new ElapsedEventHandler(WriteSomething);
timer.Start();
}
private void WriteSomething(objectsource, System.Timers.ElapsedEventArgs e)
{
FileStream fs = null;
try
{
fs = new FileStream("d:/1.txt", FileMode.OpenOrCreate);
string strText = @"//執行個體化一個檔案流--->與寫入檔案相關聯
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
//執行個體化一個StreamWriter-->與fs相關聯
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(this.textBox1.Text);
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.Close();";
//獲得位元組數組
byte[] data = new UTF8Encoding().GetBytes(strText);
//開始寫入
fs.Write(data, 0, data.Length);
//清空緩衝區、關閉流
fs.Flush();
fs.Close();
fs.Dispose();
}
catch
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}
}
}
3.然後切換到設計檢視,右鍵點擊中圈選的“添加安裝程式
4.選中第一個控制項,點擊F4,右邊切換到屬性視圖;更改屬性視圖中的Account屬性為LocalService(本地服務)
5.選中上面第二個控制項,點擊F4,右邊切換到屬性視圖。更改ServiceName為你自己喜歡的服務名稱,記住不要和系統的衝突了,StartType預設為手動,你可以更改為自動
(Automatic)或禁用(Disabled)
6.編譯項目,然後win+R輸入cmd進入命令視窗。去對應.net版本下的目錄中找到InstallUtil.exe,我項目採用的是 .net 4.0,故路徑為C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
7.InstallUtil.exe對應.net版本目錄圖,如下
8.然後win+R輸入cmd進入命令視窗。
9.
方法刪除服務:直接進行註冊表編輯 開啟登錄編輯程式,找到下面的索引值:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services 一般服務會以相同的名字在這裡顯示一個主健,直接刪除相關的索引值便可。
建立Windows服務簡單流程