C# – How to detect the first time a ClickOnce-deployed application has been run

cclickoncenet

I have a ClickOnce-deployed application and I'm currently using this to detect the first time a new deployment is being run:

if (ApplicationDeployment.IsNetworkDeployed
    && ApplicationDeployment.CurrentDeployment.IsFirstRun)
{
    // Display release notes so user knows what's new
}

It seems to works as expected after ClickOnce performs an automatic update.

But it doesn't work at all when the user goes to publish.htm on the install site and installs a newer version manually. Is there a way to detect both of these conditions reliably?

Edit: The situation I'm trying to account for: sometimes users hear that an update has been released and manually go to publish.htm to get the new version, instead of launching the application and letting ClickOnce handle the upgrade. To ClickOnce, this is apparently indistinguishable from a first-time install. Is that true?

Solution Code: I ended up creating a ClickOnce helper class with the following key section:

    public static bool IsFirstRun
    {
        get
        {
            if (!IsNetworkDeployed)
                return false; // not applicable == bool default value

            if (!File.Exists(VersionFileName))
                return true;

            return (GetLastRunVersion() != Version.ToString());
        }
    }

    public static void StoreCurrentVersion()
    {
        File.WriteAllText(VersionFileName, Version.ToString());
    }

    public static string GetLastRunVersion()
    {
        using (var stream = File.OpenText(VersionFileName))
        {
            return stream.ReadToEnd();
        }
    }

    public static string VersionFileName
    {
        get
        {
            StringBuilder filename = new StringBuilder(Files.LocalFilesPath);
            if (!filename.ToString().EndsWith(@"\"))
                filename.Append(@"\");
            filename.Append(@"versioninfo.dat");
            return filename.ToString();
        }
    }

Best Answer

Include an extra file in your ClickOnce install called justInstalled.txt (or something). Chedk for that file when the app starts. If you find it delete it and run any code for your first run of that deployment. The file will stay missing until the next deployment/upgrade.