C# 软件自动更新程序(七)

本文详细介绍了如何使用C#编程实现软件的自动更新功能,涵盖了从检查更新到下载安装的完整流程,帮助开发者提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoUpgrade.Models;
using System.Xml.Linq;
using System.Net;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Diagnostics;

namespace AutoUpgrade.BL
{
    public class XmlFileHandle
    {
        public  List<UpdataFileModel> updataFileList = null;

        public List<UpdataFileModel> interUpdataFileList = null;
        public List<UpdataFileModel> localUpdataFileList = null;

        private string localRootPath = string.Empty;
        private string ReleaseAddress = string.Empty;
         private string InternetUpdateFile = string.Empty;
        private string LocalUpdateFile = string.Empty;

        private static XmlFileHandle _instance = null;
        public static XmlFileHandle Instance()
        {
            if (_instance == null)
            {
                _instance = new XmlFileHandle();
            }
            return _instance;
        }

        public XmlFileHandle()
        {
            localRootPath = Application.StartupPath;
            ReleaseAddress = ConfigurationManager.AppSettings["ReleaseAddress"];
            InternetUpdateFile = ConfigurationManager.AppSettings["InternetUpdateFile"];
            LocalUpdateFile = ConfigurationManager.AppSettings["LocalUpdateFile"];

        }

        #region 检查更新文件是否有新的补丁

        /// <summary>
        /// 检查更新文件是否有新的补丁
        /// </summary>
        /// <returns></returns>
        public bool CheckUpdateFile()
        {
            DateTime localupDate = GetLocalUpdateFileReleaseTime();
            DateTime internetUpDate = GetInterUpdateFileReleaseTime();
            if (DateTime.Compare(internetUpDate, localupDate) > 0)
            {
                LoadLocalUpdateFileAll();
                return true;
            }
            return false;

            

        }

        private DateTime GetLocalUpdateFileReleaseTime()
        {
            string path = localRootPath + "\\" + LocalUpdateFile;
            return GetUpdateFileReleaseTime(path);
        }

        private DateTime GetInterUpdateFileReleaseTime()
        {
            string path = InternetUpdateFile;
            return GetUpdateFileReleaseTime(path);
        }

        private DateTime GetUpdateFileReleaseTime(string strpath)
        {
            if (string.IsNullOrEmpty(strpath))
                return DateTime.MinValue;
            try
            {
                XElement root = XElement.Load(strpath);
                if (!string.IsNullOrEmpty(root.Attribute("ReleaseTime").Value))
                    return Convert.ToDateTime(root.Attribute("ReleaseTime").Value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return DateTime.MinValue;
        }
        #endregion        

        #region 读取更新文件到数据集合List<FolderInfoModel>中
        /// <summary> 
        /// 获取Internet文件列表并下载 
        /// </summary> 
        private List<FolderInfoModel> ReadInternetUpdateList()
        {
            string path = InternetUpdateFile;
            return  ReadUpdateList(path);
        }

        /// <summary>
        /// 获取Local文件列表
        /// </summary>
        /// <returns></returns>
        private List<FolderInfoModel> ReadLocalUpdateList()
        {
            string path = localRootPath + "\\" + LocalUpdateFile;
            return ReadUpdateList(path);
        }

        private List<FolderInfoModel> ReadUpdateList(string path)
        {
            List<FolderInfoModel> list = null;
            try
            {
                XElement root = XElement.Load(path);
                list = ReadRootXml(root.Element("FolderInfo"));
                return list;

            }
            catch (WebException ex)
            {
                AutoUpgradeBO.MeBox(ex.Message);
            }
            return null;
        }

        private List<FolderInfoModel> ReadRootXml(XElement folderElement)
        {
            try
            {
                if (folderElement == null)
                    return null;
                List<FolderInfoModel> list = new List<FolderInfoModel>();

                FolderInfoModel model = new FolderInfoModel();
                foreach (var att in folderElement.Attributes())
                {
                    if (att.Name == "FolderName")
                        model.FolderName = att.Value;
                    if (att.Name == "FolderPath")
                        model.FolderPath = att.Value;
                    if (att.Name == "CreateTime")
                        model.CreateTime = Convert.ToDateTime(att.Value);
                }
                model.FileList = ReadFileXml(folderElement);
                model.ChildFolder = ReadFolderXml(folderElement);
                list.Add(model);
                return list;
            }
            catch (Exception ex)
            {
                AutoUpgradeBO.MeBox(ex.Message);
            }
            return null;
        }

        private List<FileInfoModel> ReadFileXml(XElement folderElement)
        {
            try
            {
                List<FileInfoModel> list = new List<FileInfoModel>();
                FileInfoModel model = null;
                foreach (var item in folderElement.Elements("FileInfo"))
                {
                    model = new FileInfoModel();
                    foreach (var att in item.Attributes())
                    {
                        if (att.Name == "FileName")
                            model.FileName = att.Value;
                        if (att.Name == "FilePath")
                            model.FilePath = att.Value;
                        if (att.Name == "CreateTime")
                            model.CreateTime = Convert.ToDateTime(att.Value);
                        if (att.Name == "ModifyTime")
                            model.ModifyTime = Convert.ToDateTime(att.Value);
                        if (att.Name == "FileSize")
                            model.FileSize = Convert.ToInt64(att.Value);
                        if (att.Name == "Version")
                            model.Version = att.Value;
                    }
                    list.Add(model);
                }
                return list;
            }
            catch (Exception ex)
            {
                AutoUpgradeBO.MeBox(ex.Message);
            }
            return null;
        }

        private List<FolderInfoModel> ReadFolderXml(XElement folderElement)
        {
            try
            {
                List<FolderInfoModel> list = new List<FolderInfoModel>();
                FolderInfoModel model = null;
                foreach (var item in folderElement.Elements("FolderInfo"))
                {
                    model = new FolderInfoModel();
                    foreach (var att in item.Attributes())
                    {
                        if (att.Name == "FolderName")
                            model.FolderName = att.Value;
                        if (att.Name == "FolderPath")
                            model.FolderPath = att.Value;
                        if (att.Name == "CreateTime")
                            model.CreateTime = Convert.ToDateTime(att.Value);
                    }
                    model.FileList = ReadFileXml(item);

                    model.ChildFolder=ReadFolderXml(item);
                    list.Add(model);
                }
                return list;
            }
            catch (Exception ex)
            {
                AutoUpgradeBO.MeBox(ex.Message);
            }
            return null;
        }
        #endregion

        public List<UpdataFileModel> GetAnalysisUpdateFileByModifyTime()
        {
            List<FolderInfoModel> interUpdateList = ReadInternetUpdateList();
            List<FolderInfoModel> localUpdateList = ReadLocalUpdateList();

            List<UpdataFileModel> interList = new List<UpdataFileModel>();
            GetUpdateFolderList(interUpdateList[0], interList);
            List<UpdataFileModel> localList = new List<UpdataFileModel>();
            GetUpdateFolderList(localUpdateList[0], localList);

            IEnumerable<UpdataFileModel> result = interList.Except(localList);

            return result.ToList();

        }
        private void GetUpdateFolderList(FolderInfoModel model,List<UpdataFileModel> upModel)
        {
            List<UpdataFileModel> list = GetUpdateFileList(model);
            if (list != null)
            {
                upModel.AddRange(list);
            }

            if (model.ChildFolder != null && model.ChildFolder.Count > 0)
            {
                foreach (var item in model.ChildFolder)
                {
                    GetUpdateFolderList(item, upModel);
                }
            }
            
        }

        private List<UpdataFileModel> GetUpdateFileList(FolderInfoModel model)
        {
            if (model.FileList == null || model.FileList.Count <= 0)
                return null;
            IEnumerable<UpdataFileModel> list = model.FileList.Select(p =>
                new UpdataFileModel
                {
                    FileName = p.FileName,
                    LocalPath = Application.StartupPath + p.FilePath + "\\" + p.FileName,
                    UrlPath = ReleaseAddress + p.FilePath.Replace("\\", "/") + "/" + p.FileName,
                    FileSize = p.FileSize,
                    Version = p.Version,
                    ModifyTime = p.ModifyTime
                });
            return list.ToList();                    
        }

        #region 检查数据集合与本地文件比对,返回具体更新列表 

        public UpdataFileModel[] GetLocalUpdateFileAll()
        {
            if (updataFileList != null)
            {
                return updataFileList.ToArray();
            }
            return null;
        }

        private void LoadLocalUpdateFileAll()
        {
            List<FolderInfoModel> list = ReadInternetUpdateList();
            updataFileList = new List<UpdataFileModel>();
            updataFileList = GetAnalysisUpdateFileByModifyTime();
            CheckLocalDir(list[0], updataFileList);
        }

        private void CheckLocalDir(FolderInfoModel folder,List<UpdataFileModel> list)
        {
            if (folder.ChildFolder == null || folder.ChildFolder.Count() <= 0)
                return;
             string path = string.Empty;
             CheckLocalFile(folder, list);
            foreach (var item in folder.ChildFolder)
            {
                path =localRootPath +item.FolderPath;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }               
               CheckLocalFile(item, list);
               CheckLocalDir(item, list);
            }
            
        }

        private void CheckLocalFile(FolderInfoModel folder, List<UpdataFileModel> list)
        {            
            if (folder.FileList == null || folder.FileList.Count() <= 0)
                return;
            string filePath = string.Empty;
            string _versin = string.Empty;
            UpdataFileModel model = null;
            foreach (var item in folder.FileList)
            {
                filePath = Application.StartupPath + item.FilePath + "\\" + item.FileName;
                model = new UpdataFileModel
                                {
                                    FileName = item.FileName,
                                    LocalPath = filePath,
                                    UrlPath = ReleaseAddress + item.FilePath.Replace("\\", "/") + "/" + item.FileName,
                                    FileSize = item.FileSize
                                };
                if (File.Exists(filePath))
                {
                    if (filePath.IndexOf(".dll")>=0 || filePath.IndexOf(".exe")>=0)
                    {
                        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(filePath);
                        _versin = fileVersionInfo.ProductVersion;
                        if (_versin !=null && item.Version != _versin)
                        {
                            if (list.Where(p=>p.FileName == model.FileName).Count()<=0)
                               list.Add(model);
                        }
                        
                    }
                }
                else
                {
                    if (list.Where(p => p.FileName == model.FileName).Count() <= 0)
                        list.Add(model);
                }
            }
        }

        #endregion

    }
}


 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AutoUpgrade.Models
{
    public class FileInfoModel
    {
        private string _filename = string.Empty;
        public string FileName
        {
            get
            {
                return _filename;
            }
            set
            {
                _filename = value;
            } 
           
        }

        public string FilePath
        {
            get;
            set;
        }

        public string RelativePath
        {
            get;
            set;
        }

        public string FileExt
        {
            get;
            set;
        }

        public long FileSize
        {
            get;
            set;
        }

        public DateTime CreateTime
        {
            get;
            set;
        }

        public DateTime ModifyTime
        {
            get;
            set;
        }
        private string _versin = string.Empty;
        public string Version
        {
            get
            {
                return _versin;
            }
            set
            {
                _versin = value;
            }
        }


        private int _productmajorpart =0;
        public int ProductMajorPart
        {
            get
            {
                return _productmajorpart;
            }
        }

        public bool IsFilter
        {
            get;
            set;
        }

         public FolderInfoModel ParentFolder
        {
            get;
            set;
        }

       


    }
}


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AutoUpgrade.Models
{
    public class FolderInfoModel
    {
        public string FolderName
        {
            get;
            set;
        }

        public string FolderPath
        {
            get;
            set;
        }

        public FolderInfoModel ParentFolder
        {
            get;
            set;
        }

        public List<FolderInfoModel> ChildFolder
        {
            get;
            set;
        }

        public List<FileInfoModel> FileList
        {
            get;
            set;
        }

        public DateTime CreateTime
        {
            get;
            set;
        }

        public bool IsFilter
        {
            get;
            set;
        }

        public XElement GetModelXml()
        {
            XElement xml = new XElement("FolderInfo",
                new XAttribute("FolderName", this.FolderName),
                new XAttribute("CreateTime", this.CreateTime.ToString()));
            return xml;
        }



    }
}


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoUpgrade.Models
{
    public class UpdataFileModel : IEquatable<UpdataFileModel>
    {
        public string FileName
        {
            get;
            set;
        }
        public string LocalPath
        {
            get;
            set;
        }
        public string UrlPath
        {
            get;
            set;
        }

        public long FileSize
        {
            get;
            set;
        }

        public DateTime ModifyTime
        {
            get;
            set;
        }

        public string Version
        {
            get;
            set;
        }

        public bool Equals(UpdataFileModel other)
        {
            //Check whether the compared object is null.
            if (Object.ReferenceEquals(other, null)) return false;

            //Check whether the compared object references the same data.
            if (Object.ReferenceEquals(this, other)) return true;

            //Check whether the products' properties are equal.
            return FileName.Equals(other.FileName) && ModifyTime.Equals(other.ModifyTime);
        }

        public override int GetHashCode()
        {

            //Get hash code for the Name field if it is not null.
            int hashProductName = FileName == null ? 0 : FileName.GetHashCode();

            //Get hash code for the Code field.
            int hashProductCode = ModifyTime.GetHashCode();

            //Calculate the hash code for the product.
            return hashProductName ^ hashProductCode;
        }

    }
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值