版本兼容

https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5

  1. <startup useLegacyV2RuntimeActivationPolicy="true">
  2. <supportedRuntime version="v4.0"/>
  3. <supportedRuntime version="v2.0.50727"/>
  4. </startup>

查询目前系统所用的.net framework版本

  1. reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\full" /v version

.NET Framework 4.x 程序到底运行在哪个 CLR 版本之上

vs2019 创建Windows Service

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.ServiceProcess;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace TestWindowsService
  12. {
  13. public partial class Service1 : ServiceBase
  14. {
  15. public Service1()
  16. {
  17. InitializeComponent();
  18. }
  19. protected override void OnStart(string[] args)
  20. {
  21. try
  22. {
  23. this.WriteLog("Start Service!");
  24. this.ToDoSomeThings();
  25. }
  26. catch(Exception ex)
  27. {
  28. }
  29. }
  30. protected override void OnStop()
  31. {
  32. }
  33. private void ToDoSomeThings()
  34. {
  35. DateTime dateTime = DateTime.Now;
  36. if(dateTime.Hour == 14 && dateTime.Minute == 30)
  37. {
  38. int a = 0;
  39. for(int i=0;i<1000; i++)
  40. {
  41. a += i;
  42. }
  43. this.WriteLog(a.ToString());
  44. }
  45. }
  46. private void WriteLog(string LogContent)
  47. {
  48. string FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Log.txt";
  49. FileStream fileStream = null;
  50. if(File.Exists(FilePath))
  51. {
  52. fileStream = new FileStream(FilePath, FileMode.Append);
  53. }
  54. else
  55. {
  56. fileStream = new FileStream(FilePath, FileMode.OpenOrCreate);
  57. }
  58. StreamWriter streamWriter = new StreamWriter(fileStream);
  59. streamWriter.WriteLine(DateTime.Now + System.Environment.NewLine + LogContent);
  60. streamWriter.Close();
  61. fileStream.Close();
  62. GC.Collect();
  63. }
  64. }
  65. }

安装/卸载 Windows Service

要以管理员的身份启动powershell或者cmd

安装服务

  1. C:\windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe D:\workspace\workspace_net\Test
  2. WindowsService\TestWindowsService\bin\Debug\TestWindowsService.exe

卸载服务

  1. C:\windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /u D:\workspace\workspace_net\Test
  2. WindowsService\TestWindowsService\bin\Debug\TestWindowsService.exe

启动服务

  1. net start service_name

停止服务

  1. net stop service_name

C# NET framework - 图1