Web Service 系列 → 智能升级也简单(用Web Services制作升级程序)

升级程序的制作有多种方法,下面介绍一种用Web Services制作的升级程序。通过Web Services 升级程序就象读写本机文件一样简单。所以我就直接给出代码。

 

Web Services部分代码:

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.IO;

 

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

    public Service()

    {

        //如果使用设计的组件,请取消注释以下行

        //InitializeComponent();

    }

    /// <summary>

    /// 需要升级文件的服务器路径

    /// </summary>

    private const string UpdateServerPath ="d://Debug";

    [WebMethod(Description = "返回服务器上程序的版本号")]

    public string ServerVer()

    {

        return "4.0";

    }

    [WebMethod(Description = "返回需更新的文件")]

    public string[] NewFiles()

    {

        DirectoryInfo di = new DirectoryInfo(UpdateServerPath);

        FileInfo[] fi = di.GetFiles();

        int intFiles= fi.Length;

        string[] myNewFiles = new string[intFiles];

        int i = 0;

        foreach (FileInfo fiTemp in fi)

        {

            myNewFiles[i] = fiTemp.Name;

            System.Diagnostics.Debug.WriteLine(fiTemp.Name);

            i++;

        }

 

        return myNewFiles;

    }

    [WebMethod(Description = "返回需更新的文件的大小")]

    public int AllFileSize()

    {

        int filesize = 0;

        string[] files = Directory.GetFiles(UpdateServerPath);

        foreach (string file in files)

        {

            FileInfo myInfo = new FileInfo(file);

            filesize += (int)myInfo.Length / 1024;

        }

        return filesize;

    }

 

    [WebMethod(Description = "返回给定文件的字节数组")]

    public byte[] GetNewFile(string requestFileName)

    {

        ///得到服务器端的一个文件

        if (requestFileName != null || requestFileName != "")

            return getBinaryFile(UpdateServerPath + "//"+requestFileName);

        else

            return null;

    }

 

    /// <summary>

    /// 返回所给文件路径的字节数组。

    /// </summary>

    /// <param name="filename"></param>

    /// <returns></returns>

    private byte[] getBinaryFile(string filename)

    {

        if (File.Exists(filename))

        {

            try

            {

                //打开现有文件以进行读取。

                FileStream s = File.OpenRead(filename);

                return ConvertStreamToByteBuffer(s);

            }

            catch

            {

                return new byte[0];

            }

        }

        else

        {

            return new byte[0];

        }

    }

    /// <summary>

    /// 把给定的文件流转换为二进制字节数组。

    /// </summary>

    /// <param name="theStream"></param>

    /// <returns></returns>

    private byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)

    {

        int b1;

        System.IO.MemoryStream tempStream = new System.IO.MemoryStream();

        while ((b1 = theStream.ReadByte()) != -1)

        {

            tempStream.WriteByte(((byte)b1));

        }

        return tempStream.ToArray();

    }

 

}

 

升级程序代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

using System.Xml;

using System.IO;

using System.Diagnostics;

 

namespace AutoUpdate

{

    public partial class frmAutoUpdate : Form

    {

        public frmAutoUpdate()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 当前版本

        /// </summary>

        private string m_strLocalVer;

        /// <summary>

        /// 服务器版本

        /// </summary>

        private string m_strServerVer;

        /// <summary>

        /// 需要更新的文件总数

        /// </summary>

        private int m_intFilesCount = 0;

        /// <summary>

        /// 需要更新的文件大小

        /// </summary>

        private int m_AllFileSize;

        /// <summary>

        /// 正在下载的文件大小

        /// </summary>

        private int m_downingFileSize;

        /// <summary>

        /// 已经下载的文件大小

        /// </summary>

        private int m_downedFileSize;

        /// <summary>

        ///数组,需要更新的文件

        /// </summary>

        private string[] m_Files = null;

        /// <summary>

        /// 定义文件对象

        /// </summary>

        WebReference.Service ws;

        /// <summary>

        /// 连接WebServeces并下载文件线程

        /// </summary>

        private Thread DownThread;

        private void frmAutoUpdata_Load(object sender, EventArgs e)

        {

            DownThread = new Thread(new ThreadStart(StartUpdate));

            DownThread.Start();

        }

        /// <summary>

        /// 连接服务器,开始升级

        /// </summary>

        private void StartUpdate()

        {

            ws = new WebReference.Service();

            m_AllFileSize = ws.AllFileSize();

            try

            {

                m_strLocalVer =Config.Ver; //从配置文件中读取当前版本号

                m_strServerVer = ws.ServerVer();//保存服务器版本号

 

                BeginInvoke(new System.EventHandler(UpdateUI), lblLink);

                //当前版本低于服务器版本,开始更新...

                if (double.Parse(m_strLocalVer) < double.Parse(m_strServerVer))

                {

                    BeginInvoke(new System.EventHandler(UpdateUI), lblDownLoad);

                    m_Files = ws.NewFiles();//需要更新的文件

                    if (m_Files != null)

                    {

                        m_intFilesCount = m_Files.Length;

                        for (int i = 0; i <= m_intFilesCount - 1; i++)

                        {

                            DownFile(m_Files[i]);

                            Debug.WriteLine(m_Files[i]);

                        }

                        // Config.VER = strServerVer;//将版本号记录到配置文件中

                    }

                }

                else

                {

                    BeginInvoke(new EventHandler(OnShowMessage),

                        "你计算机上安装的已经是最新版本了,不需要升级.");

                    return;

                }

            }

            catch (Exception ex)

            {

                BeginInvoke(new EventHandler(OnShowMessage), ex.Message);

                return;

            }

            //UI线程设置label属性

            BeginInvoke(new System.EventHandler(UpdateUI), lblStartExe);

            //安装文件

            MethodInvoker miSetup = new MethodInvoker(this.StartSetup);

            this.BeginInvoke(miSetup);

        }

        /// <summary>

        /// 下载文件

        /// </summary>

        /// <param name="fileName">文件名</param>

        private void DownFile(string fileName)

        {

            //得到二进制文件字节数组;

            byte[] bt = ws.GetNewFile(fileName);

            m_downingFileSize = bt.Length / 1024;

            string strPath = Application.StartupPath + "//Update//" + fileName;

            if (File.Exists(strPath))

            {

                File.Delete(strPath);

            }

            FileStream fs = new FileStream(strPath, FileMode.CreateNew);

            fs.Write(bt, 0, bt.Length);

            fs.Close();

        }

        /// <summary>

        /// 开始安装下载的文件

        /// </summary>

       private void StartSetup()

        {

            // 结束当前运行的主程序

            Process[] pros = Process.GetProcesses();

            for (int i = 0; i < pros.Length; i++)

            {

                if (pros[i].ProcessName == "教师考勤系统")

                {

                    pros[i].Kill();

                }

            }

            // 开始复制文件

            for (int i = 0; i <= m_intFilesCount - 1; i++)

            {

                string sourceFileName = Application.StartupPath + "//Update//" + m_Files[i];

                string destFileName = Application.StartupPath + "//" + m_Files[i];

                if (File.Exists(destFileName))

                {

                    File.Delete(destFileName);

                }

                File.Copy(sourceFileName, destFileName, false);

            }

            // 升级完成,启动主程序

            string StrExe = Application.StartupPath + "//教师考勤系统.exe";

 

            if (File.Exists(StrExe))

            {

                System.Diagnostics.Process.Start(StrExe);

            }

 

            //关闭升级程序

            Application.Exit();

        }

 

        #region 辅助方法,确保线程安全

 

        /// <summary>

        /// Label上显示信息

        /// </summary>

        private void UpdateUI(object sender, EventArgs e)

        {

            Label lbl = (Label)sender;

            lbl.ForeColor = SystemColors.Desktop;

            lblLocalVer.Text = m_strLocalVer;

            lblServerVer.Text = m_strServerVer;

        }

 

        /// <summary>

        /// 显示对话框

        /// </summary>

        private void OnShowMessage(object sender, EventArgs e)

        {

            MessageBox.Show(this, sender.ToString(), this.Text,

                MessageBoxButtons.OK, MessageBoxIcon.Information);

            Thread.Sleep(100);

            this.Close();

        }

        /// <summary>

        /// 显示进度条

        /// </summary>

        private void InvokePrgBar()

        {

            if (prgBar.Value < 100)

            {

                prgBar.Value = 100 * (int)m_downedFileSize / m_AllFileSize;

                prgBar.Update();

                System.Diagnostics.Debug.WriteLine("prgBar.Value:{0}" + prgBar.Value);

            }

        }

        /// <summary>

        /// 计算文件已下载的百分比

        /// </summary>

        private void subPrgBar()

        {

            m_downedFileSize += m_downingFileSize;

            System.Diagnostics.Debug.WriteLine("AllFileSize  " + m_AllFileSize);

            System.Diagnostics.Debug.WriteLine("downingFileSize  " + m_downingFileSize);

            do

            {

                Thread.Sleep(100);

                MethodInvoker mi = new MethodInvoker(this.InvokePrgBar);

                this.BeginInvoke(mi);

            } while (m_AllFileSize <= m_downedFileSize);

        }

        #endregion

 

        /// <summary>

        /// 关闭窗体时关闭线程

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void frmAutoUpdate_FormClosing(object sender, FormClosingEventArgs e)

        {

            try

            {

                DownThread.Abort();

            }

            catch

            {

                ;

            }

        }

    }

}

 

 

效果图:
 Web Service 系列 → 智能升级也简单(用Web Services制作升级程序)

你可能感兴趣的:(web services)