用c# 自动更新程序

论坛 期权论坛     
niminba   2021-5-22 14:53   54   0
<blockquote>
<p>作者:冰封一夏<br>
出处:<a href="http://www.cnblogs.com/bfyx/" rel="external nofollow" target="_blank">http://www.cnblogs.com/bfyx/</a><br>
HZHControls官网:<a href="http://www.hzhcontrols.com/" rel="external nofollow" target="_blank">http://www.hzhcontrols.com</a></p>
</blockquote>
<p>首先看获取和更新的接口</p>
<p>更新程序Program.cs</p>
<div class="blockcode">
<pre class="brush:csharp;">
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Update
{
  static class Program
  {
    /// &lt;summary&gt;
    /// 更新程序启动后复制自身,使用副本进行更新
    /// -h 不显示界面
    /// -c 不使用copy更新程序
    /// -d 更新完成删除自身,通常用在copy的更新程序
    /// -b 更新下载到备份文件,不替换原文件
    /// -r 更新完成运行的文件,下一个参数为文件路径
    /// -k 如果系统正在运行则干掉
    /// &lt;/summary&gt;
    [STAThread]
    static void Main(string[] args)
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.ThreadException += Application_ThreadException;

      List&lt;string&gt; lst = args.ToList();
      if (!lst.Contains("-b") &amp;&amp; !lst.Contains("-k"))
      {
        //这里判断成程序是否退出
        if (Process.GetProcessesByName("serviceclient").Length &gt; 0)
        {
          MessageBox.Show("服务正在运行,请退出后重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
          return;
        }
      }

      if (lst.Contains("-k"))
      {
        var ps = Process.GetProcessesByName("serviceclient");
        if (ps.Length &gt; 0)
        {
          ps[0].Kill();
        }
      }

      //副本更新程序运行
      if (!lst.Contains("-c"))//不存在-c 则进行复制运行
      {
        string strFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), Guid.NewGuid().ToString() + ".exe");
        File.Copy(Application.ExecutablePath, strFile);
        lst.Add("-c");
        lst.Add("-d");
        Process.Start(strFile, string.Join(" ", lst));
      }
      else
      {
        Action actionAfter = null;
        //将更新文件替换到当前目录
        if (!lst.Contains("-b"))
        {
          actionAfter = () =&gt;
          {
            string strUpdatePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UpdateCache\\");
            if (Directory.Exists(strUpdatePath) &amp;&amp; Directory.GetFiles(strUpdatePath).Length &gt; 0)
            {
              CopyFile(strUpdatePath, System.AppDomain.CurrentDomain.BaseDirectory, strUpdatePath);
              if (File.Exists(Path.Combine(strUpdatePath, "ver.xml")))
                File.Copy(Path.Combine(strUpdatePath, "ver.xml"), Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ver.xml"), true);
              Directory.Delete(strUpdatePath, true);
            }
          };
        }
        try
        {
          //隐藏运行
          if (!lst.Contains("-h"))
          {
            Application.Run(new FrmUpdate(actionAfter, true));
          }
          else
          {
            FrmUpdate frm = new FrmUpdate(actionAfter);
            frm.Down();
          }
        }
        catch (Exception ex)
        { }
        //运行更新后的文件
        if (lst.Contains("-r"))
        {
          int index = lst.IndexOf("-r");
          if (index + 1 &lt; lst.Count)
          {
            string strFile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, lst[index + 1]);
            if (File.Exists(strFile))
            {
              Process.Start(strFile, "-u");
            }
          }
        }
        //删除自身
        if (lst.Contains("-d"))
        {
          DeleteItself();
        }
      }
      Application.Exit();
      Process.GetCurrentProcess().Kill();
    }

    private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
      throw new NotImplementedException();
    }
    private static void CopyFile(string strSource, string strTo, string strBasePath)
    {
      string[] files = Directory.GetFiles(strSource);
      foreach (var item in files)
      {
        string strFileName = Path.GetFileName(item).ToLower();

        if (strFileName == "ver.xml ")
        {
          continue;
        }
        //如果是版本文件和文件配置xml则跳过,复制完成后再替换这2个文件
        string strToPath = Path.Combine(strTo, item.Replace(strBasePath, ""));
        var strdir = Path.GetDirectoryName(strToPath);
        if (!Directory.Exists(strdir))
        {
          Directory.CreateDirectory(strdir);
        }
        File.Copy(item, strToPath, true);
      }
      string[] dires = Directory.GetDirectories(strSource);
      foreach (var item in dires)
      {
        CopyFile(item, strTo, strBasePath);
      }
    }


    private static void DeleteItself()
    {
      ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/C ping 1.1.1.1 -n 1 -w 1000 &gt; Nul &amp; Del " + Application.ExecutablePath);
      psi.WindowStyle = ProcessWindowStyle.Hidden;
      psi.CreateNoWindow = true;
      Process.Start(psi);
    }
  }
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP