[.NET]監控且自動重啟.exe

  • 1521
  • 0

[.NET]監控且自動重啟.exe

補一個簡單版本的:
1.c#程式碼內容

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace MonitorConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    int checkInterval;
                    Int32.TryParse(
                    System.Configuration.ConfigurationManager.AppSettings["CheckInterval"], out checkInterval);
                    if (checkInterval <= 0)
                    {
                        checkInterval = 60000;
                    }
                    string ProcessName = System.Configuration.ConfigurationManager.AppSettings["ProcessName"];

                    Process[] pro = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(ProcessName));
                    if (pro.Length == 0)
                    {
                        string ProcessPath = System.Configuration.ConfigurationManager.AppSettings["ProcessPath"];
                        if (!File.Exists(ProcessPath))
                        {
                            Console.WriteLine("\"" + ProcessPath + "\" 不存在");
                        }
                        else
                        {
                            Process.Start(ProcessPath);
                        }

                    }
                    else
                    {
                        Console.Clear();
                        Console.WriteLine("Process:" + pro[0].ProcessName + " 執行中");
                    }
                    Thread.Sleep(checkInterval);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("ex:" + ex.ToString());
                    Console.ReadLine();
                }
            }
        }
    }
}

2. app.config
 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--Log路徑-->
    <add key="ProcessPath" value="D:\Software\FSCapture v5.3.exe"/>
    <add key="ProcessName" value="FSCapture v5.3.exe"/>
    <add key="CheckInterval" value="60000"/>
    <!--監控間隔 毫秒-->
  </appSettings>
</configuration>