ASP.NET网站版本自动更新程序及代码[转]
1、自动更新程序主要负责从服务器中获取相应的更新文件,并且把这些文件下载到本地,替换现有的文件。达到修复Bug,更新功能的目的。用户手工点击更新按钮启动更新程序。已测试。
2、环境VS2008,采用C#.NET和ASP.NET实现。
3、服务器:提供下载文件,发布出去。 文件包括:dll, xml,aspx等格式文件。其中update.xml 是记录更新文件的。
4、客户端:项目里面添加一个autoupdate.xml 文件,该文件里有连接服务器的发布更新文件的服务器地址。当客户端里userupdate.xml文件里的版本号和服务器中update.xml里的版本号对比,如果服务器的版本号高,提醒客户端更新。
5、源代码如下所示。
1)、服务端发布至IIS如下图所示。
图1

其中bin目录下的dll文件属性写入打勾。
图2

Update.xml源码如下所示。
代码 <update>
<version>1.0.1.9</version>
<datetime>2009-12-14 </datetime>
<filelist filescount="5" itemcount="11" sourcepath="http://Localhost/UpdateServ/"> <file filesname="" >
<item name="xiaxia.txt" size="">
</item>
</file>
<file filesname="UpFile">
<item name="2222.dll" size="">
</item>
<item name="1162193918505.doc" size="">
</item>
<item name="xd.doc" size="">
</item>
<item name="s2.txt" size="">
</item>
<item name="a.dll" size="">
</item>
<item name="WebUPFILE.dll" size="">
</item>
</file> <file filesname="test"> <item name="aa.txt" size="">
</item>
<item name="2.txt" size="">
</item>
</file> <file filesname="Copy"> <item name="bb.doc" size="">
</item>
<item name="b.dll" size="">
</item>
</file> <file filesname="hehe"> <item name="hehe.txt" size="">
</item>
<item name="WebUPFILE.dll" size="">
</item>
</file> </filelist>
</update>
2)、客户端代码,结构如下图所示。
图3

代码内有注释,在此不再多说。
Config.cs
代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml; namespace WebUpdate
{
public class Config
{
public string url = null;
public string cmd = null; //读文件autoUpdate.xml
public Config()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "autoUpdate.xml"; try
{
if (path != null)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
url = xmlDoc.SelectSingleNode("/update/url").InnerText; }
}
catch (Exception ex)
{
throw new Exception("找不到autoUpdate.xml文件" + ex.Message); }
} //获取服务器的版本
public Version GetServerVersion()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);
return new Version(xmlDoc.SelectSingleNode("/update/version").InnerText);
} //获取客户端版本
public string GetClientVersion()
{
url = AppDomain.CurrentDomain.BaseDirectory + "userVersion.xml";
XmlDocument xmlUser = new XmlDataDocument();
xmlUser.Load(url);
XmlElement root = xmlUser.DocumentElement;
XmlNode updateNode = root.SelectSingleNode("version");
string version = updateNode.Attributes["value"].Value;
return version; } //为了进行版本比较,进行转换为整数比较
public int ConvertVersion(string value)
{
int w, z, x, y, temp;
w = int.Parse(value.Substring(, ));
z = int.Parse(value.Substring(, ));
x = int.Parse(value.Substring(, ));
y = int.Parse(value.Substring(, ));
temp = w * + z * + x * + y;
return temp;
} //更新客户版本号为服务器的版本号
public string UpdateVersion(string serVersion)
{
url = AppDomain.CurrentDomain.BaseDirectory + "userVersion.xml";
XmlDocument xmlUser = new XmlDataDocument();
xmlUser.Load(url);
XmlElement root = xmlUser.DocumentElement;
XmlNode updateNode = root.SelectSingleNode("version");
string strVer = updateNode.Attributes["value"].Value;
updateNode.Attributes["value"].Value = serVersion;
xmlUser.Save(url);
return serVersion;
} }
}
DownFile.cs
代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO; namespace WebUpdate
{
public class DownFile
{
//从服务器下载文件,若目录存在,直接复制新文件,不存在则新建目录并复制文件,成功后返回1
public bool DownFileFromServ(string url, string fileName)
{
bool downsucess = false;
try
{
string fileExtraName = url.Split(char.Parse("."))[]; //文件名
string fileAfterName = System.IO.Path.GetExtension(url); //文件的扩展名
if (fileAfterName == ".aspx")
url = fileAfterName + ".txt";
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = true;
HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse(); downsucess = this.CopyFileAndDirectory(myRes, fileName); }
catch (Exception e)
{
Console.WriteLine(e.ToString());
} return downsucess;
} //返回复制文件或创建目录是否成功
public bool CopyFileAndDirectory(WebResponse myResp, string fileName)
{
bool flag = true;
byte[] buffer = new byte[0x400];
try
{
int num;
//若本身已有该目录则删除
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
//创建目录更新到Updat目录下
string directoryName = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
} //指定文件fileName不存在时创建它
Stream streamRead = System.IO.File.Open(fileName, FileMode.Create); Stream responseStream = myResp.GetResponseStream(); do
{
//从当前读取的字节流数,复制
num = responseStream.Read(buffer, , buffer.Length);
if (num > )
{
streamRead.Write(buffer, , num);
}
}
while (num > );
streamRead.Close();
responseStream.Close();
}
catch
{
flag = false;
} return flag; } }
}
Update.cs
代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; namespace WebUpdate
{
public class Update
{
//从服务器文件update.xml中获取要下载的文件列表
public bool flag = false; public string[] GetFileList(string url)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);
XmlElement root = xmlDoc.DocumentElement;
XmlNode updateNode = root.SelectSingleNode("filelist");
string soucePath = updateNode.Attributes["sourcepath"].Value; string fileName = null;
string fileList = null;
//取出服务器里update.xml里更新的file文件
XmlNodeList fileNode = updateNode.SelectNodes("file");
if (fileNode != null)
{
foreach (XmlNode i in fileNode)
{
foreach (XmlNode j in i)
{
if (i.Attributes["filesname"].Value != "")
fileName = soucePath + i.Attributes["filesname"].Value + "/" + j.Attributes["name"].Value +
"$" + i.Attributes["filesname"].Value + "/" + j.Attributes["name"].Value;
else
fileName = soucePath + j.Attributes["name"].Value +
"$" + j.Attributes["name"].Value; fileName += ",";
fileList += fileName;
}
} string[] splitFile = fileList.Split(',');
flag = true;
return splitFile;
}
return null;
} }
}
autoUpdate.xml
<update>
<url>http://Localhost/UpdateServ/update.xml</url>
</update>
userVersion.xml
<?xml version="1.0" encoding="utf-8"?>
<update>
<version value="1.0.1.9">客户端版本号</version>
</update>
Update.aspx
代码 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Update.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>自动更新</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<asp:Label ID="lblDisplay" runat="server" style="text-align: center" mce_style="text-align: center"
Text="Label" Visible="False"></asp:Label>
<br />
<br />
<asp:Button ID="btnUpdate" runat="server" style="text-align: center" mce_style="text-align: center"
Text="更新" onclick="btnUpdate_Click" Visible="False" Height="34px"
Width="145px" />
<br />
<br />
<asp:Label ID="NewVersion" runat="server" Text="Label1" Visible="false"></asp:Label>
<br />
<br />
<asp:Label ID="CurrentVersion" runat="server" Text="Label2" Visible="false"></asp:Label>
</div>
</form>
</body>
</html>
Update.aspx.cs
代码 using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WebUpdate; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblDisplay.Text = "";
btnUpdate.Visible = false; Config cf = new Config(); NewVersion.Text = cf.GetServerVersion().ToString();
CurrentVersion.Text = cf.GetClientVersion().ToString(); int clientversion = cf.ConvertVersion(CurrentVersion.Text);
int serverversion = cf.ConvertVersion(NewVersion.Text);
if (serverversion > clientversion)
{
btnUpdate.Visible = true;
}
else
{
lblDisplay.Text = "已是最新版本,不需要更新!";
lblDisplay.Visible = true;
} }
protected void btnUpdate_Click(object sender, EventArgs e)
{
string url = null;
string[] files = null;
Config updatecf = new Config();
url = updatecf.url;
Update upd = new Update();
files = upd.GetFileList(url); UpdateFile(files); CurrentVersion.Text = updatecf.UpdateVersion(NewVersion.Text); lblDisplay.Text = "更新完成。";
lblDisplay.Visible = true;
btnUpdate.Visible = false; } private void UpdateFile(string[] files)
{
if ((files == null) || (files.Length <= ))
{
Response.Write("升级完成");
}
else
{
int num = ;
for (int i = ; i < files.Length; i++)
{
string str = files[i];
if ((str != null) && (str.Split(new char[] { '$' }).Length == ))
{
string[] strArray = str.Split(new char[] { '$' });
this.UpdateFile(strArray[], strArray[]);
num++;
}
}
if (num == )
{
Response.Write("升级完成");
}
}
} private void UpdateFile(string url, string filename)
{
string fileName = AppDomain.CurrentDomain.BaseDirectory + filename;
try
{
DownFile file = new DownFile();
bool flag = file.DownFileFromServ(url, fileName);
}
catch
{ }
}
}
ASP.NET网站版本自动更新程序及代码[转]的更多相关文章
- C#.Net版本自动更新程序及3种策略实现
C#.Net版本自动更新程序及3种策略实现 C/S程序是基于客户端和服务器的,在客户机编译新版本后将文件发布在更新服务器上,然后建立一个XML文件,该文件列举最新程序文件的版本号及最后修改日期.如程序 ...
- C#之tcp自动更新程序
.NETTCP自动更新程序有如下几步骤: 第一步:服务端开启监听 ServiceHost host; private void button1_Click(object sender, EventAr ...
- winform自动更新程序实现
一.问题背景 本地程序在实际项目使用过程中,因为可以操作电脑本地的一些信息,并且对于串口.OPC.并口等数据可以方便的进行收发,虽然现在软件行业看着动不动都是互联网啊啥的,大有Web服务就是高大上的感 ...
- C# WINFORM的自动更新程序
自动更新程序AutoUpdate.exe https://git.oschina.net/victor596jm/AutoUpdate.git 1.获取源码 http://git.oschina.ne ...
- winform 通用自动更新程序
通用自动更新程序 主要功能: 1. 可用于 C/S 程序的更新,集成到宿主主程序非常简单和配置非常简单,或不集成到主程序独立运行. 2. 支持 HTTP.FTP.WebService等多种更新下载方式 ...
- .Net自动更新程序GeneralUpdate,适用于wpf,winfrom,控制台应用
什么是GeneralUpdate: GeneralUpdate是基于.net framwork4.5.2开发的一款(c/s应用)自动升级程序. 第一个版本叫Autoupdate(原博客: WPF自动更 ...
- WPF自动更新程序
WPF AutoUpdater 描述: WPF+MVVM实现的自动更新程序 支持更新包文件验证(比较文件MD5码) 支持区分x86与x64程序的更新 支持更新程序的版本号 支持执行更新策略 截图: 使 ...
- Android App版本自动更新
App在开发过程中,随着业务场景的不断增多,功能的不断完善,早期下载App的用户便无法体验最新的功能,为了能让用户更及时的体验App最新版本,在App开发过程加入App自动更新功能便显得尤为重要.更新 ...
- android自动更新程序,安装完以后就什么都没有了,没有出现安装成功的界面的问题
转载自: http://blog.csdn.net/lovexieyuan520/article/details/9250099 在android软件开发中,总是需要更新版本,所以当有新版本开发的时候 ...
随机推荐
- react 评论列表插入评论数据 unshift
// unshift 新增数据放到最上面 //插入 回复/发表 评论else if(action.type === INSERT_COMMENT ){ let content = action.tex ...
- 学习OpenCV——HOG+SVM
#include "cv.h" #include "highgui.h" #include "stdafx.h" #include < ...
- Matlab的XTickLabel中数值带下标
%axis为'x'或'y',分别表示更改x或y刻度 %ticks是字符cell function settick(axis,ticks) n=length(ticks); tkx=get(gca,'X ...
- JQuery MultiSelect(左右选择框)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Java语言中,类所拥有的“孩子”,他们的关系是怎样的
学习了一本有关Java的书.初步了解了一些面向对象的内容. java是由一个个的类组成的,这些类组成了java程序.类之下有他的孩子,这四个孩子分别是: 成员变量:就相当于一个个的变量,他由stati ...
- android opengl
引用:http://weimingtom.iteye.com/blog/1616972 二维坐标系变换为原点在左上角(测试用) * GLES * JOGL * LWJGL * libgdx(使用g2d ...
- 12. 星际争霸之php设计模式--模板模式
题记==============================================================================本php设计模式专辑来源于博客(jymo ...
- Failed to execute request because the App-Domain could not be created.
原错误信息: 服务器应用程序不可用 您试图在此 Web 服务器上访问的 Web 应用程序当前不可用.请点击 Web 浏览器中的“刷新”按钮重试您的请求. 管理员注意事项: 详述此特定请求失败原因的错误 ...
- delphi TIdHTTP Post乱码问题
这里主要说的是中文乱码的问题 1. 发过去的是乱码如下处理, 服务器采用的是UFT-8编码的情况下 uses HTTPApp; sPost := HTTPEncode(UTF8Encode ...
- 最有效地优化 Microsoft SQL Server 的性能
为了最有效地优化 Microsoft SQL Server 的性能,您必须明确当情况不断变化时,性能将在哪些方面得到最大程度的改进,并集中分析这些方面.否则,在这些问题上您可能花费大量的时间和精力 ...