熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

c#在線升級

2013-11-13 09:39:42  來源: .NET編程 

  面介紹一種用Web Services制作的升級程序通過Web Services 升級程序就象讀寫本機文件一樣簡單所以我就直接給出代碼

  Web Services部分代碼
    using System;
    using SystemWeb;
    using SystemWebServices;
    using SystemWebServicesProtocols;
    using SystemIO;

  [WebService(Namespace = )]
    [WebServiceBinding(ConformsTo = WsiProfilesBasicProfile_)]
    public class Service : SystemWebServicesWebService
    {
        public Service()
        {
            //如果使用設計的組件請取消注釋以下行
            //InitializeComponent();
        }
        /// <summary>
        /// 需要升級文件的服務器路徑
        /// </summary>
        private const string UpdateServerPath =d:\\Debug;
        [WebMethod(Description = 返回服務器上程序的版本號)]
        public string ServerVer()
        {
            return ;
        }
        [WebMethod(Description = 返回需更新的文件)]
        public string[] NewFiles()
        {
            DirectoryInfo di = new DirectoryInfo(UpdateServerPath);
            FileInfo[] fi = diGetFiles();
            int intFiles= fiLength;
            string[] myNewFiles = new string[intFiles];
            int i = ;
            foreach (FileInfo fiTemp in fi)
            {
                myNewFiles[i] = fiTempName;
                SystemDiagnosticsDebugWriteLine(fiTempName);
                i++;
            }

  return myNewFiles;
        }
        [WebMethod(Description = 返回需更新的文件的大小)]
        public int AllFileSize()
        {
            int filesize = ;
            string[] files = DirectoryGetFiles(UpdateServerPath);
            foreach (string file in files)
            {
                FileInfo myInfo = new FileInfo(file);
                filesize += (int)myInfoLength / ;
            }
            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 (FileExists(filename))
            {
                try
                {
                    //打開現有文件以進行讀取
                    FileStream s = FileOpenRead(filename);
                    return ConvertStreamToByteBuffer(s);
                }
                catch
                {
                    return new byte[];
                }
            }
            else
            {
                return new byte[];
            }
        }
        /// <summary>
        /// 把給定的文件流轉換為二進制字節數組
        /// </summary>
        /// <param name=theStream></param>
        /// <returns></returns>
        private byte[] ConvertStreamToByteBuffer(SystemIOStream theStream)
        {
            int b;
            SystemIOMemoryStream tempStream = new SystemIOMemoryStream();
            while ((b = theStreamReadByte()) != )
            {
                tempStreamWriteByte(((byte)b));
            }
            return tempStreamToArray();
        }

  }

  升級程序代碼
    using System;
    using SystemCollectionsGeneric;
    using SystemComponentModel;
    using SystemData;
    using SystemDrawing;
    using SystemText;
    using SystemWindowsForms;
    using SystemThreading;
    using SystemXml;
    using SystemIO;
    using SystemDiagnostics;

  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 = ;
            /// <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>
            WebReferenceService ws;
            /// <summary>
            /// 連接WebServeces並下載文件線程
            /// </summary>
            private Thread DownThread;
            private void frmAutoUpdata_Load(object sender EventArgs e)
            {
                DownThread = new Thread(new ThreadStart(StartUpdate));
                DownThreadStart();
            }
            /// <summary>
            /// 連接服務器開始升級
            /// </summary>
            private void StartUpdate()
            {
                ws = new WebReferenceService();
                m_AllFileSize = wsAllFileSize();
                try
                {
                    m_strLocalVer =ConfigVer; //從配置文件中讀取當前版本號
                    m_strServerVer = wsServerVer();//保存服務器版本號

  BeginInvoke(new SystemEventHandler(UpdateUI) lblLink);
                    //當前版本低於服務器版本開始更新
                    if (doubleParse(m_strLocalVer) < doubleParse(m_strServerVer))
                    {
                        BeginInvoke(new SystemEventHandler(UpdateUI) lblDownLoad);
                        m_Files = wsNewFiles();//需要更新的文件
                        if (m_Files != null)
                        {
                            m_intFilesCount = m_FilesLength;
                            for (int i = ; i <= m_intFilesCount ; i++)
                            {
                                DownFile(m_Files[i]);
                                DebugWriteLine(m_Files[i]);
                            }
                            // ConfigVER = strServerVer;//將版本號記錄到配置文件中
                        }
                    }
                    else
                    {
                        BeginInvoke(new EventHandler(OnShowMessage)
                            你計算機上安裝的已經是最新版本了不需要升級);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    BeginInvoke(new EventHandler(OnShowMessage) exMessage);
                    return;
                }
                //UI線程設置label屬性
                BeginInvoke(new SystemEventHandler(UpdateUI) lblStartExe);
                //安裝文件
                MethodInvoker miSetup = new MethodInvoker(thisStartSetup);
                thisBeginInvoke(miSetup);
            }
            /// <summary>
            /// 下載文件
            /// </summary>
            /// <param name=fileName>文件名</param>
            private void DownFile(string fileName)
            {
                //得到二進制文件字節數組
                byte[] bt = wsGetNewFile(fileName);
                m_downingFileSize = btLength / ;
                string strPath = ApplicationStartupPath + \\Update\\ + fileName;
                if (FileExists(strPath))
                {
                    FileDelete(strPath);
                }
                FileStream fs = new FileStream(strPath FileModeCreateNew);
                fsWrite(bt btLength);
                fsClose();
            }
            /// <summary>
            /// 開始安裝下載的文件
            /// </summary>
           private void StartSetup()
            {
                // 結束當前運行的主程序
                Process[] pros = ProcessGetProcesses();
                for (int i = ; i < prosLength; i++)
                {
                    if (pros[i]ProcessName == 教師考勤系統)
                    {
                        pros[i]Kill();
                    }
                }
                // 開始復制文件
                for (int i = ; i <= m_intFilesCount ; i++)
                {
                    string sourceFileName = ApplicationStartupPath + \\Update\\ + m_Files[i];
                    string destFileName = ApplicationStartupPath + \\ + m_Files[i];
                    if (FileExists(destFileName))
                    {
                        FileDelete(destFileName);
                    }
                    FileCopy(sourceFileName destFileName false);
                }
                // 升級完成啟動主程序
                string StrExe = ApplicationStartupPath + \\教師考勤系統exe;

  if (FileExists(StrExe))
                {
                    SystemDiagnosticsProcessStart(StrExe);
                }

  //關閉升級程序
                ApplicationExit();
            }

  #region 輔助方法確保線程安全

  /// <summary>
            /// Label上顯示信息
            /// </summary>
            private void UpdateUI(object sender EventArgs e)
            {
                Label lbl = (Label)sender;
                lblForeColor = SystemColorsDesktop;
                lblLocalVerText = m_strLocalVer;
                lblServerVerText = m_strServerVer;
            }

  /// <summary>
            /// 顯示對話框
            /// </summary>
            private void OnShowMessage(object sender EventArgs e)
            {
                MessageBoxShow(this senderToString() thisText
                    MessageBoxButtonsOK MessageBoxIconInformation);
                ThreadSleep();
                thisClose();
            }
            /// <summary>
            /// 顯示進度條
            /// </summary>
            private void InvokePrgBar()
            {
                if (prgBarValue < )
                {
                    prgBarValue = * (int)m_downedFileSize / m_AllFileSize;
                    prgBarUpdate();
                    SystemDiagnosticsDebugWriteLine(prgBarValue:{} + prgBarValue);
                }
            }
            /// <summary>
            /// 計算文件已下載的百分比
            /// </summary>
            private void subPrgBar()
            {
                m_downedFileSize += m_downingFileSize;
                SystemDiagnosticsDebugWriteLine(AllFileSize  + m_AllFileSize);
                SystemDiagnosticsDebugWriteLine(downingFileSize  + m_downingFileSize);
                do
                {
                    ThreadSleep();
                    MethodInvoker mi = new MethodInvoker(thisInvokePrgBar);
                    thisBeginInvoke(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
                {
                    DownThreadAbort();
                }
                catch
                {
                    ;
                }
            }
        }
    }


From:http://tw.wingwit.com/Article/program/net/201311/11273.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.