前言
小编目前工作是大屏数据可视化,由于都是单点本地部署,版本统一和更细就成为了一个需要解决的问题,于是在跟后端同事的共同谈论下,完成了远程在线更新的功能,下面将实现逻辑和主要代码分享给大家
功能可以实现,但不一定是最优解,有更优解法的大佬也烦请友情指出,谢谢!!
实现逻辑
每次登录前,接口请求后台管理的版本号,如果与本地版本号不同,则启动下载程序,下载线上最新包。
1、工程中添加版本号管理,无论是unity自带的版本号还是自己添加
2、接口请求后台最新版本号,如果与本地版本号不同,则启动下载程序,关闭当前程序,具体实现逻辑要与后端同事配合
3、新建控制台程序,右键工程,选择”管理NuGet程序包“,在浏览中引入SharpZipLib,线上的包只能是zip格式压缩包
4、引入System.Net,使用webClient,下载URL中的资源
/// <param name="url">下载路径</param>
/// <param name="saveFilePath">保存路径,带文件名称及后缀名</param>
static void LoadZip(string url, string saveFilePath)
{
Console.WriteLine("下载软件包...");
using (WebClient wc = new WebClient())
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
wc.DownloadProgressChanged += wc_DownloadProgressChanged; // 下载中,可获取到下载进度
wc.DownloadFileCompleted += Wc_DownloadFileCompleted; // 下载完成
wc.DownloadFileAsync(new Uri(url), saveFilePath);
}
Console.ReadKey();
}
/// 下载进度
static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("downloaded {0} of {1} bytes. {2} % complete...",
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
5、下载完成后,使用第三步中引入的SharpZipLib,将下载的zip压缩包进行解压并替换原文件
static void Wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Console.WriteLine("下载完成");
UnpackFiles("文件路径,包含文件名", "文件所在文件夹路径");
}
static void UnpackFiles(string file, string dir)
{
try
{
Console.WriteLine("解压文件:" + file);
Console.WriteLine("解压到:" + dir);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding gbk = Encoding.GetEncoding("gbk");
ZipInputStream s = new ZipInputStream(File.Open(file, FileMode.Open));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
Console.WriteLine(directoryName + fileName);
if (directoryName != String.Empty)
{
Directory.CreateDirectory(dir + directoryName);
}
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(dir + theEntry.Name);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
if (File.Exists(file))
{
File.Delete(file);//覆盖后,删除无用的压缩包
}
Console.WriteLine("更新完成");
System.Environment.Exit(0);//关闭自己
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("错误:" + e.ToString());
throw;
}
}
6、解压完成后,控制台程序会自动关闭,之后打开unity程序即可完成在线更新
博主有一些实用的Unity插件,请到【https://gitee.com/jacobkay】中的查看,感谢支持