首先声明,本人文笔不好,大家见笑,欢迎高手吐槽.
做c/s开发肯定会遇到的就是自动升级功能,而这实现方式是非常多. 本文使用 webservice的方式来提供升级服务
首先准备服务
为了方便我们专门用一个文件夹来存放需要更新的应用程序
因为觉得通过新版本来更新很麻烦,所以验证文件是否需要更新用md5来判断
WebService:
public string GetVer()
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("update"));
var list = new List<object>();
var url = string.Format("http://{0}:{1}/update/", HttpContext.Current.Request.Url.Host,
HttpContext.Current.Request.Url.Port); DirectoryInfoHelper.SetDirectoryInfo(dir, list, url, "");
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(list);
}
相关方法:
public static void SetDirectoryInfo(DirectoryInfo dir, List<object> list, string url, string dirName)
{
foreach (var file in dir.GetFiles())
{
FileStream fs = File.OpenRead(file.FullName);
list.Add(new { file.Name, Md5 = Security.GetMd5(fs), LocalHost = url, Directory = dirName });
fs.Close();
}
foreach (var dirInfo in dir.GetDirectories())
{
SetDirectoryInfo(dirInfo, list, url, string.Format("{0}{1}/", dirName, dirInfo.Name));
}
}
说明:1.不创建模型,而服务端只需要提供数据,所以采用匿名对象
2.GetVer服务返回信息中 包含 文件名,md5值,域名地址,该文件上级目录
C/S:
先看界面
现在就跟着提示消息走吧.
1.获取服务文件特征
调用webservice获取文件信息
private List<VerMd5Date> GetServerData()
{
AutoUpdate.Update update = new AutoUpdate.Update();
var json = update.GetVer();
var list = AppCode.JsonHelper.JsonDeserialize<VerMd5Dates>(json);
return list;
}
客户端需要反序列化json 所以建了一个对应model
public class VerMd5Date
{
public string Name { get; set; }
public string Md5 { get; set; }
public string LocalHost { get; set; }
public string Directory { get; set; }
}
class VerMd5Dates : List<VerMd5Date>
{
}
反序列化:
/// <summary>
/// 反序列化json
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="jsonString">json字符串</param>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
2.获取本地文件特征
private List<VerMd5Date> GetLocalData(List<string> serverNames)
{
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);
var list = new List<VerMd5Date>();
DirectoryInfoHelper.GetDirectoryInfo(dir, list,"",serverNames);
return list;
}
相关方法:
public static void GetDirectoryInfo(DirectoryInfo dir, List<VerMd5Date> list, string dirName, List<string> serverNames)
{
foreach (var file in dir.GetFiles().Where(m=>serverNames.Contains(dirName+m.Name)))
{
using (FileStream fs = File.OpenRead(file.FullName))
{
list.Add(new VerMd5Date
{
Name = file.Name,
Directory = dirName,
Md5 = Security.GetMd5(fs)
});
}
}
foreach (var dirInfo in dir.GetDirectories())
{
GetDirectoryInfo(dirInfo, list, string.Format("{0}{1}/", dirName, dirInfo.Name), serverNames);
}
}
说明:serverNames 是服务器文件名集合,主要用来排除本地文件夹中非本程序文件
3.对比文件差异
private List<VerMd5Date> EqualsList(List<VerMd5Date> list, List<VerMd5Date> localList)
{
var getList = new List<VerMd5Date>();
foreach (var ver in list)
{
var file = localList.FirstOrDefault(m => m.Name == ver.Name && m.Directory == ver.Directory);
if (file == null)
{
getList.Add(ver);
}
else
{
if (file.Md5 != ver.Md5 && file.Directory == ver.Directory)
{
getList.Add(ver);
}
}
}
return getList;
}
4.下面就开始下载吧
foreach (var file in _getList)
{
SetItem(string.Format("正在下载 {0}{1}", file.Directory, file.Name));
DownloadFile(file.LocalHost, file.Directory, file.Name, progressBar1);
}
DownloadFile:
public void DownloadFile(string localHost, string dirName, string filename, ProgressBar prog)
{
try
{
WebRequest rq = WebRequest.Create(string.Format("{0}{1}{2}", localHost, dirName, filename));
WebResponse rp = rq.GetResponse(); if (prog != null)
{
SetProg((int) rp.ContentLength, );
}
string path = string.Format("{0}/{1}", Application.StartupPath, dirName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Stream newFile = File.Create(string.Format("{0}{1}", dirName, filename));
Stream serviceFile = rp.GetResponseStream();
if (serviceFile == null)
return; long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = serviceFile.Read(by, , by.Length);
while (osize > )
{
if (!cbCpu.Checked)
Thread.Sleep(); newFile.Write(by, , osize);
osize = serviceFile.Read(by, , by.Length);
if (prog == null)
continue; totalDownloadedByte = osize + totalDownloadedByte;
SetProg((int) totalDownloadedByte, );
}
newFile.Close();
serviceFile.Close();
SetItem("下载完成");
}
catch(Exception e)
{
SetItem(string.Format("---程序异常:{0}", e.Message));
}
}
下载方式有很多,这里已经有了文件的下载地址,下载代码大家就尽情发挥.有什么好的方式也告诉我一下,非常感谢
运行截图
基本上就完了.欢迎高手吐槽.
很多朋友说dll文件无法下载,本人测试时没问题的.
还有其他特殊文件如cs,config.这里提供2中解决方案
1.先压缩,下载完后解压
2.改后缀,什么后缀随意,只要排除特殊不能下载的后缀