C# WinForm怎么实现自动更新程序

2023-06-20

这篇文章主要讲解了“C# WinForm怎么实现自动更新程序”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C# WinForm怎么实现自动更新程序”吧!

开发环境

.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>
 //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");
        }

    }
}

实现效果

感谢各位的阅读,以上就是“C# WinForm怎么实现自动更新程序”的内容了,经过本文的学习后,相信大家对C# WinForm怎么实现自动更新程序这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是本站,小编将为大家推送更多相关知识点的文章,欢迎关注!