WinForm 自动更新程序(一)
				
									
					
					
						|  | 
							admin 2023年2月27日 10:14
								本文热度 1937 | 
					
				 
				     在C/S这种模式中,自动更新程序就显得尤为重要,它不像B/S模式,直接发布到服务器上,浏览器点个刷新就可以了。由于涉及到客户端文件,所以必然需要把相应的文件下载下来。这个其实比较常见,我们常用的微信、QQ等,也都是这个操作。
自动更新程序也分为客户端和服务端两部分,客户端就是用来下载的一个小程序,服务端就是供客户端调用下载接口等操作。
这里第一步先将服务端代码写出来,逻辑比较简单,使用xml文件分别存储各个文件的名称以及版本号(每次需要更新的时候,将需要更新的文件上传到服务器后,同步增加一下xml文件中对应的版本号)。然后比对客户端传进来的文件版本,若服务端版本比较高,则加入到下载列表中。客户端再循环调用下载列表中的文件进行下载更新。
开发环境:.NET Core 3.1
开发工具: Visual Studio 2019
实现代码:
//xml文件<?xml version="1.0" encoding="utf-8" ?><updateList>  <url>http://localhost:5000/api/update/</url>  <files>    <file name="1.dll" version="1.0"></file>    <file name="1.dll" version="1.1"></file>    <file name="Autoupdate.Test.exe" version="1.1"></file>  </files></updateList>
    public class updateModel {        public string name { get; set; }        public string version { get; set; }    }
    public class updateModel_Out {        public string url { get; set; }        public List<updateModel> updateList { get; set; }    }
namespace Autoupdate.WebApi.Controllers {    [Route("api/[controller]/[Action]")]    [ApiController]    public class updateController : ControllerBase {
        [HttpGet]        public JsonResult Index() {            return new JsonResult(new { code = 10, msg = "success" });        }
        [HttpPost]        public JsonResult GetupdateFiles([fromBody] List<updateModel> input) {            string xmlPath = AppContext.BaseDirectory + "updateList.xml";
            XDocument xdoc = XDocument.Load(xmlPath);            var files = from f in xdoc.Root.Element("files").Elements() select new { name = f.Attribute("name").Value, version = f.Attribute("version").Value };            var url = xdoc.Root.Element("url").Value;
            List<updateModel> updateList = new List<updateModel>();            foreach(var file in files) {
                updateModel model = input.Find(s => s.name == file.name);                if(model == null || file.version.CompareTo(model.version) > 0) {                    updateList.Add(new updateModel {                        name = file.name,                        version = file.version                    });                }            }            updateModel_Out output = new updateModel_Out {                url = url,                updateList = updateList            };            return new JsonResult(output);        }
        [HttpPost]        public FileStreamResult DownloadFile([fromBody] updateModel input) {            string path = AppContext.BaseDirectory + "files\\" + input.name;            FileStream fileStream = new FileStream(path, FileMode.Open);            return new FileStreamResult(fileStream, "application/octet-stream");        }
    }}
实现效果:
只有服务端其实没什么演示的,这里先看一下更新的效果吧。

代码解析:就只介绍下控制器中的三个方法吧,Index其实没什么用,就是用来做个测试,证明服务是通的;GetupdateFiles用来比对版本号,获取需要更新的文件(这里用到了Linq To Xml 来解析xml文件,之前文章没写过这个方式,后面再补下);DownloadFile就是用来下载文件的了。
					
					
该文章在 2023/2/27 10:14:03 编辑过