Windows 服務在背景長期執行、無需使用者互動,適合記錄系統啟動、關機時間等監控需求。本文示範以 C# 建立 Windows Service,將啟動/關機時間寫入 XML,再以 WebForm + DataGrid 顯示統計報表。
Monitoring。Service1.cs 重命名 Monitoring.cs,類別名同步修改。System.IO, System.Xml 命名空間。public partial class Monitoring : ServiceBase
{
private DateTime _startTime;
private const string XmlPath = @"C:\file1.xml";
public Monitoring() => InitializeComponent();
protected override void OnStart(string[] args)
{
_startTime = DateTime.Now;
WriteStartEntry();
}
protected override void OnShutdown()
{
WriteShutdownEntry();
}
private void WriteStartEntry()
{
// 確保 XML 根節點存在
if (!File.Exists(XmlPath))
{
File.WriteAllText(XmlPath, " ");
}
var doc = new XmlDocument();
doc.Load(XmlPath);
var timeEl = doc.CreateElement("time");
timeEl.AppendChild(CreateElement(doc, "Date", DateTime.Now.ToString("dd-MM-yy")));
timeEl.AppendChild(CreateElement(doc, "Started", DateTime.Now.ToString("t")));
doc.DocumentElement.AppendChild(timeEl);
doc.Save(XmlPath);
}
private void WriteShutdownEntry()
{
var doc = new XmlDocument();
doc.Load(XmlPath);
var lastTime = doc.DocumentElement.LastChild; // 最近一筆
ProjectInstaller.cs。serviceProcessInstaller1.Account = ServiceAccount.LocalSystem。serviceInstaller1.DisplayName = serviceInstaller1.ServiceName = "Monitoring"。serviceInstaller1.StartType = ServiceStartMode.Automatic。CanShutdown = true, CanStop = true。// 開發人員命令提示字元
cd bin\Debug
installutil Monitoring.exe
// 成功顯示 "Commit Phase Completed Successfully"
重啟電腦 → 服務自動啟動 → 關機 → 查看 C:\file1.xml 記錄。
protected void Page_Load(object sender, EventArgs e)
{
string tempXml = @"C:\temp1.xml";
File.Copy(@"C:\file1.xml", tempXml, true);
// 補全未關機的記錄
var doc = new XmlDocument();
doc.Load(tempXml);
var lastTime = doc.DocumentElement.LastChild;
if (lastTime != null && lastTime["Shutdown"] == null)
{
lastTime.AppendChild(CreateElement(doc, "Shutdown", "undefined"));
lastTime.AppendChild(CreateElement(doc, "TimeSpent", "undefined"));
}
doc.Save(tempXml);
// 繫結 DataGrid
var ds = new DataSet();
ds.ReadXml(tempXml);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
// 計算總時長
double totalHours = 0;
using (var reader = new XmlTextReader(tempXml))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "TimeSpent")
{
string val = reader.ReadInnerXml();
if (val != "undefined" && TimeSpan.TryParse(val.Replace(".", ":"), out TimeSpan ts))
totalHours += ts.TotalHours;
}
}
}
Response.Write($"Total Duration: {Math.Floor(totalHours)} Hours {(totalHours % 1) * 60:F0} Minutes");
File.Delete(tempXml);
}
lock 或 Mutex),避免服務與網頁同時存取衝突。EventLog 寫入系統日誌,方便 IT 稽核。BackgroundService 部署為 Linux systemd 或 Windows 服務,跨平台更彈性。Windows Service 是長期背景作業的經典選擇。本文完整示範從服務建立、XML 記錄、安裝部署到 Web 報表呈現的流程。實務上應依據資料量、並發需求選擇適當儲存介質,並加強錯誤處理與日誌記錄。