如果应用程序在安装后第一次运行,请检查条件

C#2008 / 3.5 SP1

我想检查应用程序是否第一次运行。 我已经开发了一个应用程序,一旦安装在客户端计算机上。 我想检查它是否是第一次运行。

我已经安装了使用Windows安装程序项目。

if (System.Deployment.Application.ApplicationDeployment.CurrentDeployment.IsFirstRun) { // Do something here } 

上面的代码适用于clickonce开发。 但是我怎么能用Windows安装程序做类似的事情。

我想在应用程序安装时添加一个注册表。 当程序第一次运行时(true),请检查此注册项目。 一旦它第一次运行,编辑注册表为(false)。

但是,而不是使用注册表,有没有更好的方法,我可以使用?

在注册表外部存储应用程序数据的好地方是应用程序数据文件夹。 如果您在首次运行时创建此目录,那么您只需要在后续加载时对其进行测试。 此外,如果您的应用程序需要它,那么您就拥有了良好的数据存储位置。

 string data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; string path = Path.Combine(data, name); if (Directory.Exists(path)) { // application has been run } else { // create the directory on first run DirectoryInfo di = Directory.CreateDirectory(path); } 

只需在“应用程序设置”中添加一个布尔值即可。 最简单的方法是使用IDE和设置设计器。 它必须是用户范围,但应用程序范围不可写。

第一次检测时,不要忘记切换值并保存设置。

代码如下所示:

  if (Properties.Settings.Default.FirstUse) { Properties.Settings.Default.FirstUse = false; Properties.Settings.Default.Save(); // do things first-time only } 

注册表听起来不错 您可能希望确保在将值设置为false之前正确执行所有首次初始化,并且可以选择让用户在必要时重置此值。

您可以将文件存储在用户的帐户文件夹中,而不是乱用注册表。 我无法回想起确切的位置,但是您可以通过电话来获取用户设置文件夹的位置。

为了确定是否执行了某个应用程序,我检查了可执行文件目录中的FirstTime.txt文件。 我将该文件放在可执行文件目录中,因为我知道在卸载期间删除了该目录。 因此,当重新部署应用程序时,我确信此文件不会存在,因此我将使用静态应用程序设置来初始配置用户可以通过应用程序更改的用户设置,因为它们只是 – 用户设置。

我在触发form_closing事件时保存这些用户设置。 即使先前部署中有先前的用户设置,知道FirstTime.txt不存在(因此让我知道这是应用程序第一次启动),我确信用户设置被重置为静态应用程序设置第一次运行应用程序(当然,除非用户在关闭应用程序之前更改这些设置)。

无论如何,这里有一段代码来检查应用程序是否已被执行:

  ///  /// Check if this is the first time ADDapt has ever executed ///  ///  /// We know that ADDapt has run before with the existence of FirstTime.txt. ///  ///  /// False - this was the first time the application executed ///  ///  /// Application base directory ///  public bool CheckFirstTime(String ADDaptBinDirectory) { bool bADDaptRunFirstTime = false; String FirstTimeFileName = string.Format("{0}//FirstTime.txt", ADDaptBinDirectory); // Find FirstTime.txt in Bin Directory if (File.Exists(FirstTimeFileName)) bADDaptRunFirstTime = true; else { // Create FirstTime file } return bADDaptRunFirstTime; } ///  /// Create the FirstTime file ///  ///  /// Saving the creation date in the first time documents when the app was initially executed ///  ///  /// Full windows file name (Directory and all) ///  private void CreateFirstTimeFile(String FirstTimeFN) { FileInfo fi = new FileInfo(FirstTimeFN); DateTime dt = DateTime.Now; using (TextWriter w = fi.CreateText()) { w.WriteLine(string.Format("Creation Date: {0:g} ", dt)); } }