詳解C# WinForm如何實現(xiàn)自動更新程序
前言
在C/S這種模式中,自動更新程序就顯得尤為重要,它不像B/S模式,直接發(fā)布到服務器上,瀏覽器點個刷新就可以了。由于涉及到客戶端文件,所以必然需要把相應的文件下載下來。這個其實比較常見,我們常用的微信、QQ等,也都是這個操作。
自動更新程序也分為客戶端和服務端兩部分,客戶端就是用來下載的一個小程序,服務端就是供客戶端調用下載接口等操作。
這里第一步先將服務端代碼寫出來,邏輯比較簡單,使用xml文件分別存儲各個文件的名稱以及版本號(每次需要更新的時候,將需要更新的文件上傳到服務器后,同步增加一下xml文件中對應的版本號)。然后比對客戶端傳進來的文件版本,若服務端版本比較高,則加入到下載列表中??蛻舳嗽傺h(huán)調用下載列表中的文件進行下載更新。

開發(fā)環(huán)境
.NET Core 3.1
開發(fā)工具
Visual Studio 2019
實現(xiàn)代碼
//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> //Model
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");
}
}
}實現(xiàn)效果
只有服務端其實沒什么演示的,這里先看一下更新的效果吧。

代碼解析
就只介紹下控制器中的三個方法吧,Index其實沒什么用,就是用來做個測試,證明服務是通的;GetUpdateFiles用來比對版本號,獲取需要更新的文件(這里用到了Linq To Xml 來解析xml文件,之前文章沒寫過這個方式,后面再補下);DownloadFile就是用來下載文件的了。
到此這篇關于詳解C# WinForm如何實現(xiàn)自動更新程序的文章就介紹到這了,更多相關C# WinForm自動更新程序內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

