回覆列表
  • 1 # 使用者834195712159

    用C#建立Windows服務的步驟:

    1.建立Windows Service專案

    2.向服務中函式功能實現

    OnStart函式在啟動服務時執行,OnStop函式在停止服務時執行。在這裡,當啟動和停止服務時,向一個文字檔案中寫入一些文字資訊,

    示例程式碼如下:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Diagnostics;

    using System.IO;

    using System.Linq;

    using System.ServiceProcess;

    using System.Text;

    using System.Threading.Tasks;

    namespace MyService

    {

    public partial class Service1 : ServiceBase

    {

    public Service1()

    {

    InitializeComponent();

    }

    protected override void OnStart(string[] args)

    {

    FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);

    StreamWriter sw = new StreamWriter(fs);

    sw.BaseStream.Seek(0, SeekOrigin.End);

    sw.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n");

    sw.Flush();

    sw.Close();

    fs.Close();

    }

    //protected override void OnContinue()

    //{

    // base.OnContinue();

    //}

    //protected override void OnPause()

    //{

    // base.OnPause(); // father class method inherit

    //}

    //protected override void OnShutdown()

    //{

    // base.OnShutdown();

    //}

    protected override void OnStop()

    {

    FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);

    StreamWriter sw = new StreamWriter(fs);

    sw.BaseStream.Seek(0, SeekOrigin.End);

    sw.WriteLine("WindowsService: Service Stopped" + DateTime.Now.ToString() + "\n");

    sw.Flush();

    sw.Close();

    fs.Close();

    }

    }

    }

  • 中秋節和大豐收的關聯?
  • 描寫月的四字詞語?