本地会获取当前系统的版本号去请求后台java的接口数据。返回给我的是后台压缩包转的base64字节流。
客户端拿到新版本需要更新本地程序。
if (updatesystem(path.combine(application.startuppath, "version.txt"), path.combine(application.startuppath, "u.zip"))) { application.exit(); }
/// <summary> /// 读取本地版本请求更新 /// </summary> /// <param name="document">读取的文件信息</param> /// <param name="zippath">返回zip包本地路径</param> /// <returns></returns> private bool updatesystem(string document, string zippath) { try { dictionary<string, string> postdic = new dictionary<string, string>(); //获取文件内的版本号 if(file.exists(document)) { postdic.add("version", file.readalltext(document).trim()); } else { postdic.add("version", "0"); } string postjson = jsonconvert.serializeobject(postdic); string url = getappsettingvalue("serverurl") + "parkclient/parkclientupdate"; //返回的json数据 jobject obj = (jobject)jsonconvert.deserializeobject(postdata(postjson, url)); string newversion = obj["version"].tostring(); if (!string.isnullorwhitespace(newversion)) { byte[] bytesfile = convert.frombase64string(obj["bytearray"].tostring()); if (obj["clientmd5"].tostring() == bitconverter.tostring( new system.security.cryptography.md5cryptoserviceprovider().computehash(bytesfile)).replace("-", "")) { zipcoverage(bytesfile, zippath); file.writealltext(document, newversion); } } return true; } catch (exception ex) { messagebox.show(ex.message); return false; } } /// <summary> /// 解压zip包覆盖更新 /// </summary> /// <param name="bytes">接受更新包的字节信息</param> /// <param name="zpath">覆盖的路径</param> private void zipcoverage(byte[] bytes, string zpath) { file.writeallbytes(zpath, bytes); using (ziparchive archive = zipfile.openread(zpath)) { string file = null; foreach (ziparchiveentry entry in archive.entries) { if (!entry.fullname.endswith("/")) { file = path.combine(application.startuppath, entry.fullname); if (file.exists(file)) { file.delete(file); } } } } zipfile.extracttodirectory(zpath, application.startuppath); } /// <summary> /// 获取配置文件中的appsettings节中的配置内容 /// </summary> /// <param name="appsettingkey"></param> /// <param name="message"></param> /// <returns></returns> private string getappsettingvalue(string appsettingkey) { execonfigurationfilemap map = new execonfigurationfilemap { execonfigfilename = @"tdh.parking.client.exe.config" }; return configurationmanager.openmappedexeconfiguration(map, configurationuserlevel.none).appsettings.settings[appsettingkey].value; }
byte[] bytesfile = convert.frombase64string(obj["bytearray"].tostring());
这里是拿到的字节流了。
这个方法可以解决在同一个解决方案中有多个项目可以读取到同一个项目下的app.config文件。
注意:其中有引用到的类库, 这是是用来操作压缩包的。
说下思路:第一步其实就是拿到压缩包的字节流再保存到本地,第二步就是循环读取压缩包的文件替换本地的文件,完成本地系统的版本更新。
无论简单与复杂,都需一步步向前方迈进。
以上就是c#如何实现自动更新本地程序的实例分析的详细内容。
