当前位置:实例文章 » C#开发实例» [文章]c# 自定义安装程序路径(设置安装路径多一层目录)+卸载前执行操作

c# 自定义安装程序路径(设置安装路径多一层目录)+卸载前执行操作

发布人:shili8 发布时间:2023-06-05 08:34 阅读次数:133

在开发C#程序时,我们经常需要为程序编写安装程序,以便用户可以方便地安装和卸载程序。但是,有时候我们需要自定义安装程序的路径,或者在卸载程序之前执行一些操作。本文将介绍如何使用C#编写自定义安装程序路径和卸载前执行操作的代码。

1. 自定义安装程序路径

默认情况下,安装程序会将程序安装到“Program Files”目录下。但是,有时候我们需要将程序安装到其他目录下,或者在安装路径中添加一层目录。下面是一个示例代码,演示如何自定义安装程序路径:

csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace MyInstaller
{
    [RunInstaller(true)]
    public partial class MyInstaller : Installer
    {
        public MyInstaller()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary<string object> stateSaver)
        {
            base.Install(stateSaver);

            // 获取安装路径
            string targetDir = Context.Parameters[targetdir];

            // 在安装路径中添加一层目录
            string installDir = Path.Combine(targetDir MyApp);

            // 设置安装路径
            stateSaver.Add(InstallDir installDir);
        }

        public override void Commit(IDictionary<string object> savedState)
        {
            base.Commit(savedState);

            // 获取安装路径
            string installDir = (string)savedState[InstallDir];

            // 在安装路径中创建目录
            Directory.CreateDirectory(installDir);
        }
    }
}


在上面的代码中,我们重写了Install方法和Commit方法。在Install方法中,我们获取了安装路径,并在其中添加了一层目录。然后,我们将安装路径保存到stateSaver中,以便在后续的操作中使用。在Commit方法中,我们获取了安装路径,并在其中创建了一个目录。

2. 卸载前执行操作

有时候,我们需要在卸载程序之前执行一些操作,例如删除程序创建的文件或者清除注册表项。下面是一个示例代码,演示如何在卸载程序之前执行操作:

csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace MyInstaller
{
    [RunInstaller(true)]
    public partial class MyInstaller : Installer
    {
        public MyInstaller()
        {
            InitializeComponent();
        }

        public override void Uninstall(IDictionary<string object> savedState)
        {
            base.Uninstall(savedState);

            // 获取安装路径
            string installDir = (string)savedState[InstallDir];

            // 删除程序创建的文件
            string[] files = Directory.GetFiles(installDir);
            foreach (string file in files)
            {
                File.Delete(file);
            }

            // 清除注册表项
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(SoftwareMyApp);
            if (key != null)
            {
                Microsoft.Win32.Registry.CurrentUser.DeleteSubKey(SoftwareMyApp);
            }
        }
    }
}


在上面的代码中,我们重写了Uninstall方法。在该方法中,我们获取了安装路径,并删除了程序创建的文件。然后,我们清除了注册表项。注意,我们需要使用Microsoft.Win32.Registry类来访问注册表。

相关标签:c#windows开发语言
其他信息

其他资源

Top