C#Windws program is executed regularly, including log output function (can automatically clear expired logs)
Environment dotnet4.5, development tools vs2019
App.config file
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <!--Execution time interval, in seconds--> <add key="time" value="1800"/> <!--Whether to output the log ((0: no output 1: output))--> <add key="WriteLogs" value="1"/> <add key="ClientSettingsProvider. ServiceUri" value=""/> </appSettings> <system.web> <membership defaultProvider="ClientAuthenticationMembershipProvider"> <providers> <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" /> </providers> </membership> <roleManager defaultProvider="ClientRoleProvider" enabled="true"> <providers> <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/> </providers> </roleManager> </system.web> </configuration>
reference module
using System; using System.Data; using System. ServiceProcess; using System. Text; using System.IO; using System. Configuration; using System.Net;
My method (SkHikImg.cs) code structure
namespace SkHikImg {<!-- --> public partial class SkHikImg : ServiceBase {<!-- --> System.Timers.Timer timer = new System.Timers.Timer(); public SkHikImg()//timed execution {<!-- --> InitializeComponent(); timer.Elapsed + = new System.Timers.ElapsedEventHandler(TimedEvent); timer.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["time"]) * 1000;//Execute regularly according to the configuration file time timer.Enabled = true;//execute switch } private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e) {<!-- -->//Main logic entry timer. Enabled = false; ///your program logic/// this.WriteLog("log output, successful execution"); timer. Enabled = true; } } protected override void OnStart(string[] args) {<!-- --> this.WriteLog("【Service start】"); } protected override void OnStop() {<!-- --> this.WriteLog("【Service stop】"); } private void WriteLog(string msg)//log output {<!-- --> try {<!-- --> DelLogs(); bool WriteLogs = int.Parse(ConfigurationManager.AppSettings["WriteLogs"].ToString()) == 1 ? true : false;//Log output switch if (WriteLogs) {<!-- --> string fname = DateTime.Now.ToString("yyyyMMdd") + ".log";//Name the log file string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + string.Format("Logs\{0}", fname);//log path if (!Directory. Exists(path)) {<!-- --> Directory.CreateDirectory(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs");//Create a log path without } string line = string.Format("【{0}】{1} \r\\ ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg) ;//Output log content File.AppendAllText(path, line); } } catch (Exception) {<!-- --> } } public static void DelLogs()//Delete expired logs {<!-- --> string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs\";//log path DirectoryInfo directoryInfo = new DirectoryInfo(path); if (Directory. Exists(path)) {<!-- --> FileInfo[] fileInfos = directoryInfo. GetFiles(); DateTime date = DateTime. Now. AddDays(-7); foreach (FileInfo file in fileInfos) {<!-- --> if (date.CompareTo(file.LastWriteTime) > 0 & amp; & amp; System.Text.RegularExpressions.Regex.IsMatch(file.Name, ".log"))//log file name {<!-- --> File.Delete(path + file.Name); } } } } //Save network pictures (streams are saved as pictures) private string GetMethodImage(string pathFile, byte[] imgbit) //private string GetMethodImage(string imgUrl) {<!-- --> //string pathFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Uploads/Image/"; // Check if the folder exists if (!Directory. Exists(pathFile)) {<!-- --> Directory.CreateDirectory(pathFile); } pathFile + = $@"{<!-- -->DateTime.Now.ToString("yyMMddHHmmss")}.jpg"; //WriteBytesToFile(pathFile, GetBytesFromUrl(imgUrl)); WriteBytesToFile(pathFile, imgbit); return pathFile; } public static void WriteBytesToFile(string fileName, byte[] content) {<!-- --> FileStream fs = new FileStream(fileName, FileMode. Create); BinaryWriter w = new BinaryWriter(fs); try {<!-- --> w. Write(content); } finally {<!-- --> fs.Close(); w.Close(); } } } }
The main entrance setting (Program.cs), generally the default setting is fine
static void Main() {<!-- --> ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] {<!-- --> new SkHikImg() }; ServiceBase.Run(ServicesToRun); }
Installer Settings
1. The Account of serviceProcessInstaller1 is set to LocalSystem
2. The StartType of serviceInstaller1 should be set to Automatic
Installer
1. Write two batches and throw in the \SkHikImg\bin\Debug folder
install.bat
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe %~dp0\SkHikImg.exe net start SkHikImg pause
uninstall.bat
net stop SkHikImg C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u %~dp0\SkHikImg.exe pause
2. Generate a solution
3. Run the installation.bat with administrator privileges
End
Different environments may cause errors, please debug by yourself **–**