我有一篇关于编写Windows服务的文章,该服务检查“进程”是否处于运行/停止状态,并根据时间表运行/停止“进程”。 这是我的代码,我面临的问题是它无法运行该进程也无法停止该进程(它记录了进程的正确状态)
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += Timer_Elapsed;
timer.Interval = 60000;
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service stopped");
timer.Stop();
timer.Dispose();
}
private string processName = "notepad";
private Process process;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
WriteToFile("Notepad is run " + DateTime.Now);
process = processes[0];
if (!process.HasExited)
{
process.Kill();
WriteToFile("Notepad is stopped " + DateTime.Now);
}
}
else
{
WriteToFile("Notepad is not running " + DateTime.Now);
StartProcess();
}
}
private void StartProcess()
{
try
{
Process.Start(processName);
WriteToFile("Notepad is started " + DateTime.Now);
}
catch (Exception ex)
{
EventLog.WriteEntry("Process Monitoring Service", $"No run Notepad: {ex.Message}", EventLogEntryType.Error);
WriteToFile("Service error " + DateTime.Now);
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\B2Log_" +
DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
你可以尝试看看这个问题。希望可以帮到你。