做一个简单的控制台程序, 让他在指定的时间, 关闭指定的软件(的进程), 关闭后再打开这个软件
①创建控制台程序, 主要代码:
using System.Diagnostics;namespace AutomaticRestart
{public class Program{public static string ProcessNames = Convert.ToString(CustomConfigManager.GetConfig("ProcessNames"));//需关闭的进程名称public static int RestartTime = Convert.ToInt(CustomConfigManager.GetConfig("RestartTime"));//重启时间,单位秒public static int count = 0;public static void Main(string[] args){while (true){#region ①先关闭程序try{if (!string.IsNullOrWhiteSpace(ProcessNames)){string[] strArr = ProcessNames.Split('|');foreach (string processName in strArr){foreach (var process in System.Diagnostics.Process.GetProcessesByName(processName)){try{//Console.WriteLine($"正在关闭 {processName} 进程...");process.Kill();Console.WriteLine($"已关闭 {processName} 进程.");}catch (Exception ex){Console.WriteLine($"无法关闭 {processName} 进程: {ex.Message}");}Thread.Sleep(1000);//休息 }Thread.Sleep(1000);//休息 }}}catch (Exception ex){Console.WriteLine($"无法关闭进程: {ex.Message}");continue;//循环继续}#endregion#region ②再打开程序finally//运行程序{string filePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "ProcessRun.txt";if (File.Exists(filePath))//判断*.txt文件是否存在{string[] lines = File.ReadAllLines(filePath);//读取txt文件每一行(一行一个*.exe文件路径记录)foreach (string line in lines){try{if (File.Exists(line))//判断*.exe文件是否存在{Process.Start(line);Console.WriteLine($"{line} 启动成功...");}}catch (Exception ex){Console.WriteLine($"{line} 无法启动, {ex.Message} ");}Thread.Sleep(1000);//休息 }}}#endregion#region ③定时循环处理Console.WriteLine($"休息 {RestartTime} 秒...");//1小时=3600秒 Thread.Sleep(RestartTime * 1000);//休息if (count > 9){count = 0;Console.Clear();}else{Console.WriteLine("-------------------------------------------------");Console.WriteLine();}#endregion}}}
}
②配置文件配置
appconfig.json文件(关闭程序的进程名称):
{//需要关闭的进程名称(区分大小写),多个进程用|号间隔,如: DVR_AlarmListen|DataConvert.APP"ProcessNames": "DVR_AlarmListen|DataConvert.APP",//重启时间,单位秒(30三十秒,60一分钟,300五分钟,600十分钟,900十五分钟,1800三十分钟,3600一小时,10800三小时,14400四小时,21600六小时,28800八小时,43200十二小时)"RestartTime": 30
}
ProcessRun.txt文件(启动程序的路径):
D:\iis\DVR_AlarmListen\netcoreapp3.1\DVR_AlarmListen.exe
D:\iis\DataConvert.APP\net6.0\DataConvert.APP.exe
③读取appconfig.json的配置
using Microsoft.Extensions.Configuration;namespace AutomaticRestart
{public class CustomConfigManager{//读取配置文件:appsettings//1.Microsoft.Extensions.Configuration;//NuGet获取//2.Microsoft.Extensions.Configuration.Json;//NuGet获取 public static string GetConfig(string key){var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); //默认读取:当前运行目录IConfigurationRoot configuration = builder.Build();string configValue = configuration.GetSection(key).Value;return configValue;}}
}