在C#中安装应用程序之前执行一些操作

时间:2014-11-01 11:29:08

标签: c# .net visual-studio-2010 c#-4.0

我正在使用C#和.NET 4.0框架来开发WPF应用程序。我需要执行这样的任务:在桌面上安装我的WPF应用程序之前,我需要删除该安装桌面中的某个文件夹。我尝试了下面的一个:

File installer.cs

this.BeforeInstall +=new InstallEventHandler(Installer_BeforeInstall);

void Installer_BeforeInstall(object sender, InstallEventArgs e)
{
    // Code
}

我安装WPF应用程序后执行上述方法中用于删除文件夹/目录的代码,意味着安装的一半。我需要在WPF应用程序将安装文件夹保存在桌面上之前删除该文件夹。我如何使用.NET 4.0在C#中执行此操作?

更新:installer.cs

namespace namespace name
{
    [RunInstaller(true)]
    public partial class Installer : System.Configuration.Install.Installer
    {
        public Installer()
        {
            InitializeComponent();

            this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);

            this.BeforeUninstall += new InstallEventHandler(ServiceInstaller_BeforeUninstall);
        }

        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
        }

        void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            //code
        }

        void ServiceInstaller_BeforeUninstall(object sender, InstallEventArgs e)
        {
            // Code
        }
    }
}

1 个答案:

答案 0 :(得分:4)

删除目标系统上的文件/文件夹是危险的,应该避免。您应该只删除创建的文件;你是这里的MSI文件。现在您已被警告,以下是您的选择:

  • 使用Visual Studio安装项目,这是不可能的,或者至少不是微不足道的。您需要使用C ++实现自定义操作,编译成DLL,构建MSI,change the install sequence using Orca以在CostFinalize之前运行。

  • 使用第三方工具为安装程序项目提供更多权力,例如AdvancedInstaller

  • 如果你决定去第三方,我会说使用WiX。查看RemoveFolder操作,或者您可以使用CustomAction这样的内容:

    <CustomAction Id="DeleteFiles" Return="check" Value="del path\to\folder" />
    
    <InstallExecuteSequence>
      <Custom Action="DeleteFiles" After='InstallFinalize'>Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
      ...
    </InstallExecuteSequence>