C# 用msiexec安装

本文介绍如何在C#中利用msiexec命令行工具进行软件安装操作,重点在于处理命令行参数和异常情况。

忽略TestHarness.Logger.Log, 这是自定义的写日志的方法, 可以替换成Console.WriteLine()

 

public static int InvokeMsi(string msiFilePath, string workDir, bool wait, bool uninstall)
        {
            Process process = null;
            string arg = String.Format("/q /{0} \"{1}\"", uninstall ? "x" : "i", msiFilePath);
            ProcessStartInfo psi = new ProcessStartInfo("msiexec.exe", arg);
            psi.UseShellExecute = false;
            if (!String.IsNullOrEmpty(workDir))
            {
                psi.WorkingDirectory = workDir;
            }
            else
            {
                psi.WorkingDirectory = Environment.CurrentDirectory;
            }
            process = new Process();
            process.StartInfo = psi;
            try
            {
                TestHarness.Logger.Log("Starting to {0} using msiexec.exe" + arg, (uninstall ? "uninstall" : "install") + msiFilePath);
                process.Start();
            }
            catch (Exception ex)
            {
                TestHarness.Logger.Log("Exception: " + ex.Message);
                return -1;
            }
            if (wait)
            {
                process.WaitForExit();
                if (process.ExitCode == 0)
                {
                    TestHarness.Logger.Log("Succeeded! ");
                }
                return process.ExitCode;
            }
            else
            {
                return 0;
            }
        }

        //Install software by using msiexec
        public static int InstallMsi(string msiFilePath, string workDir, bool wait)
        {
            return InvokeMsi(msiFilePath, workDir, wait, false);
        }

        public static int UninstallMsi(string msiFilePath, string workDir, bool wait)
        {
            return InvokeMsi(msiFilePath, workDir, wait, true);
        }

    


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值