• c#如何实现自动更新


    更新思想:根据url下载安装包,再在本地解压,将图标在桌面显示。自动更新的时候使用后台线程(当程序退出的时候,线程也退出)。

     private void lbVersion_Click(object sender, RoutedEventArgs e)//设置一个按钮来确定是否自动更新
            {
                AutoUpdateManager.AutoUpdate();
            }

        public static void AutoUpdate()//将程序放入线程池中(线程池线程默认为后台线程, 应用程序的主线程以及使用Thread构造的线程都默认为前台线程,线程池线程也就是使用 ThreadPool.QueueUserWorkItem()和Task工厂创建的线程都默认为后台线程)
             {
                  ThreadPool.QueueUserWorkItem(CheckUpdateAction);
             }

      private static void CheckUpdateAction(object state)
            {
                if (state != null)//这里没啥用,防止以后加功能
                {
                    Thread.CurrentThread.Priority = (ThreadPriority)state;
                    
                }
                {
                    WorkFileService service = new WorkFileService();//new一个类
                    WorkFile file = service.NetDownAutoUpdateFiles(ConfigurationManager.AppSettings["fileBigType"], ConfigurationManager.AppSettings["fileSmallType"], CurVersion);//根据URL下载信息,根据Http下载,代码在下面
                    if (file != null && !string.IsNullOrEmpty(file.fileNo))
                    {
                        if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"DownFiles"))//穿件一个文件夹放安装程序
                        {
                            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"DownFiles");
                        }
                        string path = MakeTempUpdateAction(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"DownFiles", file.fileName));//解压程序,并在桌面上放图标
                        if (OnUpdated != null)
                        {
                            OnUpdated.Invoke(file.fileName.Replace(".zip", "").Replace(".rar", ""), path);
                        }
                    }
                    else
                    {
                        if (OnUpdated != null)
                        {
                            OnUpdated.Invoke(string.Empty, string.Empty);
                        }
                    }
                }
            }

    public class WorkFile : EntityBase
    {
    /// <summary>
    /// 文件ID
    /// </summary>
    public int fileId
    { get; set; }
    /// <summary>
    /// 文件编号
    /// </summary>
    public string fileNo
    { get; set; }
    /// <summary>
    /// 文件类型
    /// </summary>
    public int fileType
    { get; set; }
    /// <summary>
    /// 文件名
    /// </summary>
    public string fileName
    { get; set; }
    /// <summary>
    /// 文件拓展名
    /// </summary>
    public string extension
    { get; set; }
    /// <summary>
    /// 文件大小
    /// </summary>
    public int fileSize
    { get; set; }
    /// <summary>
    /// 文件路径
    /// </summary>
    public string filePath
    { get; set; }
    /// <summary>
    /// 数据标识
    /// </summary>
    public int dataFlag
    { get; set; }
    /// <summary>
    /// 文件MD5码
    /// </summary>
    public string md5
    { get; set; }
    /// <summary>
    /// 机台类型
    /// </summary>
    public string machineType
    { get; set; }
    /// <summary>
    /// 文件分组Id
    /// </summary>
    public int groupId
    { get; set; }
    /// <summary>
    /// 拓展Json
    /// </summary>
    public string json
    { get; set; }
    /// <summary>
    /// 文件顺序
    /// </summary>
    public int rowNum
    { get; set; }
    /// <summary>
    /// 版本
    /// </summary>
    public string version
    { get; set; }
    }

    
    
      public WorkFile NetDownAutoUpdateFiles(string big, string small, string version)//下载程序
            {
                WorkFile file = new WorkFile();
                string result = HttpClient.DownLoadData(ConfigurationManager.AppSettings["API_AutoUpdateProgram"], new { fileBigType = big, fileSmallType = small, fileVersion = version });//代码后面后
                if (!string.IsNullOrEmpty(result))//若返回的数据不为空,反序列化到类中
                {
                    var Msg = JsonHelper.Deserialize<ApiMessage<WorkFile>>(result);
                    if (Msg != null)
                    {
                        file = Msg.data;
                        if (file != null && !string.IsNullOrEmpty(file.fileNo))
                        {
                            if (HttpClient.HttpDownloadAutoUpdateFile(file.filePath, file.fileName, file.md5))//md5检验
                            {
                                rep.Add(file);
                            }
                            UnitOfWorkFile.Commit();//使用事务,防止下载到一半断网了
                        }
                    }
                }
                return file;
            }

    public static string DownLoadData(string url, object requestData)//根据url下载,使用post传输,用webclient下载,未转换成类,是json字符串

    {
       string ret = string.Empty;
          try
               {
                   if (!url.Contains("http"))
               {
                   url = string.Format("http://{0}:{1}/{2}/{3}", ConfigurationManager.AppSettings["ApiServerHost"], ConfigurationManager.AppSettings["ApiServerPort"], ConfigurationManager.AppSettings["ApiPrefix"], url);
                }
                 using (WebClient client = new WebClient())
               {
                   client.Encoding = Encoding.UTF8;
                   client.Headers.Add("Accept", "application/json");
                   client.Headers.Add("Content-Type", "application/json");
                   client.Headers.Add("Timeout", "5000");
                   client.Headers.Add("Method", "POST");
                   ret = client.UploadString(url, JsonHelper.Serialize(requestData));//下载数据
               }
                      }
    catch (Exception ex)
    {
    }
    return ret;
    }

     
    
    
            /// <summary>
            /// HTTP下载文件
            /// </summary>
            /// <param name="url">Http相对路径</param>
            /// <param name="fileName">文件名</param>
            /// <returns></returns>
            public static bool HttpDownloadAutoUpdateFile(string url, string fileName, string md5)
            {
                try
                {
     DownFilesPath = AppDomain.CurrentDomain.BaseDirectory + @"DownFiles";//获取文件基目录
    string filePath = DownFilesPath + fileName; using (WebClient client = new WebClient()) { url = url.Replace("192.168.50.100", ConfigurationManager.AppSettings["ApiServerHost"]); Uri uri = new Uri(string.Format("http://{0}/{1}", url, fileName)); client.DownloadFile(uri, filePath); //下载文件到指定目录 } return CheckFileMd5ByFilePath(filePath, md5);//进行md5检验确定下载文件的正确性 } catch (Exception ex) { return false; } }
     /// <summary>
               /// md5校验
               /// </summary>
               /// <param name="FilePath">文件路径</param>
               /// <returns></returns>
            private static bool CheckFileMd5ByFilePath(string FilePath, string RightMd5)
            {
                bool Right = false;
                try
                {
                    if (File.Exists(FilePath))
                    {
                        using (System.IO.FileStream fileStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open))//用的本地路径
                        {
                            using (System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                            {
                                byte[] retVal = md5.ComputeHash(fileStream);
                                string filemd5 = string.Join("", retVal.Select(b => b.ToString("x2")).ToList());
                                Right = (filemd5 == RightMd5);
                            }
                            fileStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                { 
                }
                return Right;
            }
    
    
    
    
    
    
    
            /// <summary>
            /// 操作本地临时压缩文件更新程序
            /// </summary>
            /// <param name="zipFilePath">临时压缩文件位置</param>
            private static string MakeTempUpdateAction(string zipFilePath)
            {
                if (File.Exists(zipFilePath))
                {
                    string ParentPath = Path.Combine(Path.GetFullPath("../.."),
                    string.Format("{0}{1}", "MacCheck", DateTime.Now.ToString("yyMMddHHmm")));
                    if (Directory.Exists(ParentPath))
                    {
                        Directory.Delete(ParentPath, true);
                    }
                    Directory.CreateDirectory(ParentPath);
                    if (ZipHelper.UnZip(zipFilePath, ParentPath))
                    {
                        ParentPath = Path.Combine(ParentPath, "MacCheck.Bin");
                        File.Copy(Path.GetFullPath(@"MacCheck_DB.db"), Path.Combine(ParentPath, @"MacCheck_DB.db"), true);
                        File.Copy(Path.GetFullPath(@"MacCheck.exe.config"), Path.Combine(ParentPath, @"MacCheck.exe.config"), true);
                        //File.Copy(Path.GetFullPath(@"SupConConfig.json"), Path.Combine(ParentPath, @"SupConConfig.json"), true);
                        Utils.CreateShortCut("设备点巡检", Path.Combine(ParentPath, @"MacCheck.exe"), ParentPath, "设备点检程序");
                        return Path.Combine(ParentPath, @"MacCheck.exe");
                    };
                }
                return string.Empty;
            }
    
    
    

      

     
  • 相关阅读:
    2018-2019-2 网络对抗技术 20165212 Exp4 恶意代码分析
    2018-2019-2 20165212 《网络对抗技术》Exp3 免杀原理与实践
    2018-2019-2 20165212《网络对抗技术》Exp2 后门原理与实践
    2018-2019-2 20165212《网络对抗技术》Exp1 PC平台逆向破解
    小议Android多进程以致Application多次初始化
    Android Studio Gradle编译时『No resource found that matches the given name』解决方法(windows系统的坑)
    用gradle编译任意结构的Android项目
    Android 上能提高学习工作效率的应用
    求医记(一)
    Android应用开发中的夜间模式实现(一)
  • 原文地址:https://www.cnblogs.com/xyyshishuaige/p/9037364.html
Copyright © 2020-2023  润新知