如何让Windows服务打开一个“进程”,如果它停止并且在它按照计划运行时停止

问题描述 投票:0回答:1

我有一篇关于编写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);
            }
        }
    }
}

}

c# service process
1个回答
0
投票

你可以尝试看看这个问题。希望可以帮到你。

用记事本打开文件

© www.soinside.com 2019 - 2024. All rights reserved.