程序运行了多少次? C#

如何在不保留文件和计数的情况下获得程序之前在C#中运行的次数。 如果不可能,可以从计划任务管理器获取?

致C. Ross:如何在注册表设置中完成? 原谅我。 什么是注册表设置?

据我所知,Windows不会为您保留此信息。 您必须在某处(文件,数据库,注册表设置)计算值。 Windows任务计划程序function非常低。

我在注册表设置中执行此操作。

static string AppRegyPath = "Software\\Cheeso\\ApplicationName"; static string rvn_Runs = "Runs"; private Microsoft.Win32.RegistryKey _appCuKey; public Microsoft.Win32.RegistryKey AppCuKey { get { if (_appCuKey == null) { _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true); if (_appCuKey == null) _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath); } return _appCuKey; } set { _appCuKey = null; } } public int UpdateRunCount() { int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0); x++; AppCuKey.SetValue(rvn_Runs, x); return x; } 

如果它是WinForms应用程序,您可以挂钩Form的OnClosing事件以运行UpdateCount

应用程序运行的时间存储在注册表中; 但有几点需要注意:

  1. 它存储在用户注册表中(例如HKCU) [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist]
  2. 该路径存储在ROT13中 ,例如runme.exe将成为ehazr.rkr
  3. 注册表实际上以二进制forms存储三个值:最后一个运行时,运行计数(由于某种原因,从6开始而不是1),以及应用程序的名称。

不知道这是否有帮助,但你有它!

这是一个注册表处理教程 – C#Registry Basics

您只需创建名为Properties.Settings.Default.TimesRun;的应用程序设置即可 Properties.Settings.Default.TimesRun;

像这样使用它:

 private void Form1_Load( object sender, EventArgs e ) { Properties.Settings.Default.TimesRun = timesrun++; Properties.Settings.Default.Save(); } 

不,任务经理不提供这种信息。 我不会很难创建一个脚本来更新计数然后执行应用程序,然后设置任务来调用脚本。

我建议使用Windows附带的ESENT数据库。 ESENT Managed Interface可轻松获得软件支持。

@ Cheeso ,

不需要私有成员变量与该代码,一种方法来减少它:

 using Microsoft.Win32; public RegistryKey AppCuKey { get { return Registry.CurrentUser.OpenSubKey(AppRegyPath, true) ?? Registry.CurrentUser.CreateSubKey(AppRegyPath); } } 

或者,如果您想更新私有变量,为了避免调用该方法(无论如何这是一个非常便宜的方法),您仍然可以保存自己的if == null检查。

 int x = Your_Project.Properties.Settings.Default.Counter; x++; Your_Project.Properties.Settings.Default.Counter = x; Your_Project.Properties.Settings.Default.Save();