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网站版本自动更新程序及代码[转]的更多相关文章

  1. C#.Net版本自动更新程序及3种策略实现

    C#.Net版本自动更新程序及3种策略实现 C/S程序是基于客户端和服务器的,在客户机编译新版本后将文件发布在更新服务器上,然后建立一个XML文件,该文件列举最新程序文件的版本号及最后修改日期.如程序 ...

  2. C#之tcp自动更新程序

    .NETTCP自动更新程序有如下几步骤: 第一步:服务端开启监听 ServiceHost host; private void button1_Click(object sender, EventAr ...

  3. winform自动更新程序实现

    一.问题背景 本地程序在实际项目使用过程中,因为可以操作电脑本地的一些信息,并且对于串口.OPC.并口等数据可以方便的进行收发,虽然现在软件行业看着动不动都是互联网啊啥的,大有Web服务就是高大上的感 ...

  4. C# WINFORM的自动更新程序

    自动更新程序AutoUpdate.exe https://git.oschina.net/victor596jm/AutoUpdate.git 1.获取源码 http://git.oschina.ne ...

  5. winform 通用自动更新程序

    通用自动更新程序 主要功能: 1. 可用于 C/S 程序的更新,集成到宿主主程序非常简单和配置非常简单,或不集成到主程序独立运行. 2. 支持 HTTP.FTP.WebService等多种更新下载方式 ...

  6. .Net自动更新程序GeneralUpdate,适用于wpf,winfrom,控制台应用

    什么是GeneralUpdate: GeneralUpdate是基于.net framwork4.5.2开发的一款(c/s应用)自动升级程序. 第一个版本叫Autoupdate(原博客: WPF自动更 ...

  7. WPF自动更新程序

    WPF AutoUpdater 描述: WPF+MVVM实现的自动更新程序 支持更新包文件验证(比较文件MD5码) 支持区分x86与x64程序的更新 支持更新程序的版本号 支持执行更新策略 截图: 使 ...

  8. Android App版本自动更新

    App在开发过程中,随着业务场景的不断增多,功能的不断完善,早期下载App的用户便无法体验最新的功能,为了能让用户更及时的体验App最新版本,在App开发过程加入App自动更新功能便显得尤为重要.更新 ...

  9. android自动更新程序,安装完以后就什么都没有了,没有出现安装成功的界面的问题

    转载自: http://blog.csdn.net/lovexieyuan520/article/details/9250099 在android软件开发中,总是需要更新版本,所以当有新版本开发的时候 ...

随机推荐

  1. Windows Sserver 2008 R2 搭建DNS配置区域与配置转发器上外网

    一.实验模拟环境: zhuyu公司是一家成立的新公司,该公司的局域网没有DNS服务器,所有电脑都使用电 信ISP提供的DNS服务器(202.96.128.166).zhuyu公司计划搭建一台DNS服务 ...

  2. 物理主机win 7系统迁移至VMware ESXI服务器

    一.实验环境如下图所示: 二.实验要求(如上图所示) 通过 计算机B  (IP:10.8.9.18) 将 计算机A (IP:10.8.9.155) 迁移到 服务器(IP:10.8.9.161) 三.实 ...

  3. 用jQuery实现限制输入字数的文本框

    1.导入外部.js文件: <script src="js/jquery-1.8.3.js" type="text/javascript"></ ...

  4. jquery判断页面是否滑动到最底部

    // 滚动到底部,向下的箭头消失 var $down = $('.down'); var $window = $(window); var $document = $(document); $wind ...

  5. [Android Tips] 16. Update Android SDK from command-line

    $ cd $ANROID_HOME $ tools/android update sdk -u -s 参数 -s --no-https : Uses HTTP instead of HTTPS (th ...

  6. bootstrap入门-2.固定的内置样式

    HTML5文档类型(Doctype) Bootstrap使用了一些HTML5元素和CSS属性,所以需要使用HTML5文档类型. <!DOCTYPE html> <html> . ...

  7. url传值错误

    ValueError at /add/ invalid literal for int() with base 10: ''6'' Request Method: GET Request URL: h ...

  8. 1.2 如何在visual studio 中建立C#程序

    这一节简单介绍一下怎么在visual studio 2015中建立第一个C#程序,我使用的是2015版的visual studio,不同版本可能有一些差异,不过大体上是相同的,这些信息仅供新手参考,大 ...

  9. .net 直接输出远程文件到浏览器和下载文件保存到本机

    利用了xmlhttp,实现代码比较简单具体实现如下: 首先bin文件引入,com->microsoft xml v3.0 具体代码如下: protected void Button1_Click ...

  10. web移动前端的click点透问题

    在移动端开发中,有时会出现click点透的问题. 一.什么是click点透 以下情况,在B元素上有半透明红色遮盖层A,黄色B元素内有可点击链接C. tips:以下举例仅针对webkit内核浏览器,所有 ...