zoukankan      html  css  js  c++  java
  • c# 软件自动在线更新代码

    程序部份代码参考自:http://www.cnblogs.com/hjs1573/archive/2007/09/11/889826.html

    服务器空间为.Net 2.0空间

    注意:网盘失效,源码无法下载,不过所有的源代码都已经贴出来了,可以自己新建一个工程,然后把代码复制进去,自行编译

    服务器空间文件列表:

    /UpdateSize.ashx

    /AutoUpdater   //此文件夹放更新文件

    /AutoUpdater/AutoUpdater.xml

    UpdateSize.ashx:

     1<%@ WebHandler Language="C#" Class="UpdateSize" %> 
     2
     3using System; 
     4using System.Web; 
     5using System.IO; 
     6
     7public class UpdateSize : IHttpHandler 
     8     
     9    public void ProcessRequest (HttpContext context) 
    10        string dirPath = context.Server.MapPath("/AutoUpdater/"); 
    11        context.Response.ContentType = "text/xml"
    12        context.Response.Expires = -1
    13        context.Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); 
    14        context.Response.Write("<UpdateSize Size=\"" + GetUpdateSize(dirPath) + "\" />"); 
    15        context.Response.End(); 
    16    }
     
    17
    18    /// <summary> 
    19    /// 获取所有下载文件大小 
    20    /// </summary> 
    21    /// <returns>返回值</returns> 

    22    private static long GetUpdateSize(string dirPath) 
    23    
    24        //判断文件夹是否存在,不存在则退出 
    25        if (!Directory.Exists(dirPath)) 
    26            return 0
    27        long len; 
    28        len = 0
    29        DirectoryInfo di = new DirectoryInfo(dirPath); 
    30        //获取所有文件大小 
    31        foreach (FileInfo fi in di.GetFiles()) 
    32        
    33            //剔除升级数据文件 
    34            if (fi.Name != "AutoUpdater.xml")  
    35                len += fi.Length; 
    36        }
     
    37        return len; 
    38    }
     
    39
    40    public bool IsReusable 
    41        get 
    42            return false
    43        }
     
    44    }
     
    45}

    AutoUpdater.xml:

    <?xml version="1.0" encoding="utf-8" ?>  
    <AutoUpdater>  
      
    <UpdateInfo>  
        
    <!--升级文件的更新日期-->  
        
    <UpdateTime Date = "2008-08-06"/>  
      
    </UpdateInfo>  
      
    <!--升级文件列表-->  
      
    <UpdateFileList>  
        
    <UpdateFile>Maxthon207.exe</UpdateFile>  
      
    </UpdateFileList> 
      
    <UpdateFileList>  
        
    <UpdateFile>Maxthon207.exe</UpdateFile>  
      
    </UpdateFileList>  
    </AutoUpdater> 

    客户端

    conf.config:

     

    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
      
    <appSettings> 
        
    <add key="Url" value="http://localhost/" /> 
        
    <add key="UpDate" value="2008-08-06" /> 
      
    </appSettings> 
    </configuration>

    AutoUpdater.cs:

      1using System; 
      2using System.ComponentModel; 
      3using System.Data; 
      4using System.Globalization; 
      5using System.IO; 
      6using System.Net; 
      7using System.Text; 
      8using System.Windows.Forms; 
      9using System.Xml; 
     10
     11namespace Yesuo 
     12
     13    public partial class AutoUpdater : Form 
     14    
     15        private WebClient downWebClient = new WebClient(); 
     16        private static string dirPath; 
     17        private static long size;//所有文件大小 
     18        private static int count;//文件总数 
     19        private static string[] fileNames; 
     20        private static int num;//已更新文件数 
     21        private static long upsize;//已更新文件大小 
     22        private static string fileName;//当前文件名 
     23        private static long filesize;//当前文件大小 
     24         
     25        public AutoUpdater() 
     26        
     27            InitializeComponent(); 
     28        }
     
     29
     30        private void ComCirUpdate_Load(object sender, EventArgs e) 
     31        
     32            dirPath = GetConfigValue("conf.config""Url"); 
     33            string thePreUpdateDate = GetTheLastUpdateTime(dirPath); 
     34            string localUpDate = GetConfigValue("conf.config""UpDate"); 
     35            if (!String.IsNullOrEmpty(thePreUpdateDate) && !String.IsNullOrEmpty(localUpDate)) 
     36            
     37                if (DateTime.Compare( 
     38                    Convert.ToDateTime(thePreUpdateDate, CultureInfo.InvariantCulture), 
     39                    Convert.ToDateTime(localUpDate, CultureInfo.InvariantCulture)) > 0
     40                
     41                    UpdaterStart(); 
     42                }
     
     43                else 
     44                
     45                    UpdaterClose(); 
     46                }
     
     47            }
     
     48            else 
     49            
     50                UpdaterClose(); 
     51            }
     
     52            //UpdaterStart(); 
     53        }
     
     54
     55        /// <summary> 
     56        /// 开始更新 
     57        /// </summary> 

     58        private void UpdaterStart() 
     59        
     60            float tempf; 
     61            //委托下载数据时事件 
     62            this.downWebClient.DownloadProgressChanged += delegate(object wcsender, DownloadProgressChangedEventArgs ex) 
     63            
     64                this.label2.Text = String.Format( 
     65                    CultureInfo.InvariantCulture, 
     66                    "正在下载:{0}  [ {1}/{2} ]"
     67                    fileName, 
     68                    ConvertSize(ex.BytesReceived), 
     69                    ConvertSize(ex.TotalBytesToReceive)); 
     70
     71                filesize = ex.TotalBytesToReceive; 
     72                tempf = ((float)(upsize + ex.BytesReceived) / size); 
     73                this.progressBar1.Value = Convert.ToInt32(tempf * 100); 
     74                this.progressBar2.Value = ex.ProgressPercentage; 
     75            }

     76            //委托下载完成时事件 
     77            this.downWebClient.DownloadFileCompleted += delegate(object wcsender, AsyncCompletedEventArgs ex) 
     78            
     79                if (ex.Error != null
     80                
     81                    MeBox(ex.Error.Message); 
     82                }
     
     83                else 
     84                
     85                    if (File.Exists(Application.StartupPath + "\\" + fileName)) 
     86                    
     87                        File.Delete(Application.StartupPath + "\\" + fileName); 
     88                    }
     
     89                    File.Move(Application.StartupPath + "\\AutoUpdater\\" + fileName, Application.StartupPath + "\\" + fileName); 
     90                    upsize += filesize; 
     91                    if (fileNames.Length > num) 
     92                    
     93                        DownloadFile(num); 
     94                    }
     
     95                    else 
     96                    
     97                        SetConfigValue("conf.config""UpDate", GetTheLastUpdateTime(dirPath)); 
     98                        UpdaterClose(); 
     99                    }
     
    100                }
     
    101            }

    102
    103            size = GetUpdateSize(dirPath + "UpdateSize.ashx"); 
    104            if (size == 0
    105                UpdaterClose(); 
    106            num = 0
    107            upsize = 0
    108            UpdateList(); 
    109            if (fileNames != null
    110                DownloadFile(0); 
    111        }
     
    112
    113        /// <summary> 
    114        /// 获取更新文件大小统计 
    115        /// </summary> 
    116        /// <param name="filePath">更新文件数据XML</param> 
    117        /// <returns>返回值</returns> 

    118        private static long GetUpdateSize(string filePath) 
    119        
    120            long len; 
    121            len = 0
    122            try 
    123            
    124                WebClient wc = new WebClient(); 
    125                Stream sm = wc.OpenRead(filePath); 
    126                XmlTextReader xr = new XmlTextReader(sm); 
    127                while (xr.Read()) 
    128                
    129                    if (xr.Name == "UpdateSize"
    130                    
    131                        len = Convert.ToInt64(xr.GetAttribute("Size"), CultureInfo.InvariantCulture); 
    132                        break
    133                    }
     
    134                }
     
    135                xr.Close(); 
    136                sm.Close(); 
    137            }
     
    138            catch (WebException ex) 
    139            
    140                MeBox(ex.Message); 
    141            }
     
    142            return len; 
    143        }
     
    144
    145        /// <summary> 
    146        /// 获取文件列表并下载 
    147        /// </summary> 

    148        private static void UpdateList() 
    149        
    150            string xmlPath = dirPath + "AutoUpdater/AutoUpdater.xml"
    151            WebClient wc = new WebClient(); 
    152            DataSet ds = new DataSet(); 
    153            ds.Locale = CultureInfo.InvariantCulture; 
    154             
    155            try 
    156            
    157                Stream sm = wc.OpenRead(xmlPath); 
    158                ds.ReadXml(sm); 
    159                DataTable dt = ds.Tables["UpdateFileList"]; 
    160                StringBuilder sb = new StringBuilder(); 
    161                count = dt.Rows.Count; 
    162                for (int i = 0; i < dt.Rows.Count; i++
    163                
    164                    if (i == 0
    165                    
    166                        sb.Append(dt.Rows[i]["UpdateFile"].ToString()); 
    167                    }
     
    168                    else 
    169                    
    170                        sb.Append("," + dt.Rows[i]["UpdateFile"].ToString()); 
    171                    }
     
    172                }
     
    173                fileNames = sb.ToString().Split(','); 
    174                sm.Close(); 
    175            }
     
    176            catch (WebException ex) 
    177            
    178                MeBox(ex.Message); 
    179            }
     
    180        }
     
    181
    182        /// <summary> 
    183        /// 下载文件 
    184        /// </summary> 
    185        /// <param name="arry">下载序号</param> 

    186        private void DownloadFile(int arry) 
    187        
    188            try 
    189            
    190                num++
    191                fileName = fileNames[arry]; 
    192                this.label1.Text = String.Format( 
    193                    CultureInfo.InvariantCulture, 
    194                    "更新进度 {0}/{1}  [ {2} ]",  
    195                    num,  
    196                    count,  
    197                    ConvertSize(size)); 
    198
    199                this.progressBar2.Value = 0
    200                this.downWebClient.DownloadFileAsync( 
    201                    new Uri(dirPath + "AutoUpdater/" + fileName), 
    202                    Application.StartupPath + "\\AutoUpdater\\" + fileName); 
    203            }
     
    204            catch (WebException ex) 
    205            
    206                MeBox(ex.Message); 
    207            }
     
    208        }
     
    209
    210        /// <summary> 
    211        /// 转换字节大小 
    212        /// </summary> 
    213        /// <param name="byteSize">输入字节数</param> 
    214        /// <returns>返回值</returns> 

    215        private static string ConvertSize(long byteSize) 
    216        
    217            string str = ""
    218            float tempf = (float)byteSize; 
    219            if (tempf / 1024 > 1
    220            
    221                if ((tempf / 1024/ 1024 > 1
    222                
    223                    str = ((tempf / 1024/ 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "MB"
    224                }
     
    225                else 
    226                
    227                    str = (tempf / 1024).ToString("##0.00", CultureInfo.InvariantCulture) + "KB"
    228                }
     
    229            }
     
    230            else 
    231            
    232                str = tempf.ToString(CultureInfo.InvariantCulture) + "B"
    233            }
     
    234            return str; 
    235        }
     
    236
    237        /// <summary> 
    238        /// 弹出提示框 
    239        /// </summary> 
    240        /// <param name="txt">输入提示信息</param> 

    241        private static void MeBox(string txt) 
    242        
    243            MessageBox.Show( 
    244                txt, 
    245                "提示信息"
    246                MessageBoxButtons.OK, 
    247                MessageBoxIcon.Asterisk, 
    248                MessageBoxDefaultButton.Button1, 
    249                MessageBoxOptions.DefaultDesktopOnly); 
    250        }
     
    251
    252        /// <summary> 
    253        /// 关闭程序 
    254        /// </summary> 

    255        private static void UpdaterClose() 
    256        
    257            try 
    258            
    259                System.Diagnostics.Process.Start(Application.StartupPath + "\\ComCir.exe"); 
    260            }
     
    261            catch (Win32Exception ex) 
    262            
    263                MeBox(ex.Message); 
    264            }
     
    265            Application.Exit(); 
    266        }
     
    267
    268        /// <summary> 
    269        /// 读取.exe.config的值 
    270        /// </summary> 
    271        /// <param name="path">.exe.config文件的路径</param> 
    272        /// <param name="appKey">"key"的值</param> 
    273        /// <returns>返回"value"的值</returns> 

    274        internal static string GetConfigValue(string path, string appKey) 
    275        
    276            XmlDocument xDoc = new XmlDocument(); 
    277            XmlNode xNode; 
    278            XmlElement xElem = null
    279            try 
    280            
    281                xDoc.Load(path); 
    282
    283                xNode = xDoc.SelectSingleNode("//appSettings"); 
    284
    285                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"" + appKey + "\"]"); 
    286                 
    287            }
     
    288            catch (XmlException ex) 
    289            
    290                MeBox(ex.Message); 
    291            }
     
    292            if (xElem != null
    293                    return xElem.GetAttribute("value"); 
    294                else 
    295                    return ""
    296        }
     
    297
    298        /// <summary> 
    299        /// 设置.exe.config的值 
    300        /// </summary> 
    301        /// <param name="path">.exe.config文件的路径</param> 
    302        /// <param name="appKey">"key"的值</param> 
    303        /// <param name="appValue">"value"的值</param> 

    304        internal static void SetConfigValue(string path, string appKey, string appValue) 
    305        
    306            XmlDocument xDoc = new XmlDocument(); 
    307            try 
    308            
    309                xDoc.Load(path); 
    310
    311                XmlNode xNode; 
    312                XmlElement xElem1; 
    313                XmlElement xElem2; 
    314
    315                xNode = xDoc.SelectSingleNode("//appSettings"); 
    316
    317                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key=\"" + appKey + "\"]"); 
    318                if (xElem1 != null) xElem1.SetAttribute("value", appValue); 
    319                else 
    320                
    321                    xElem2 = xDoc.CreateElement("add"); 
    322                    xElem2.SetAttribute("key", appKey); 
    323                    xElem2.SetAttribute("value", appValue); 
    324                    xNode.AppendChild(xElem2); 
    325                }
     
    326                xDoc.Save(Application.StartupPath + "\\" + path); 
    327            }
     
    328            catch (XmlException ex) 
    329            
    330                MeBox(ex.Message); 
    331            }
     
    332        }
     
    333
    334        /// <summary> 
    335        /// 判断软件的更新日期 
    336        /// </summary> 
    337        /// <param name="Dir">服务器地址</param> 
    338        /// <returns>返回日期</returns> 

    339        private static string GetTheLastUpdateTime(string Dir) 
    340        
    341            string LastUpdateTime = ""
    342            string AutoUpdaterFileName = Dir + "AutoUpdater/AutoUpdater.xml"
    343            try 
    344            
    345                WebClient wc = new WebClient(); 
    346                Stream sm = wc.OpenRead(AutoUpdaterFileName); 
    347                XmlTextReader xml = new XmlTextReader(sm); 
    348                while (xml.Read()) 
    349                
    350                    if (xml.Name == "UpdateTime"
    351                    
    352                        LastUpdateTime = xml.GetAttribute("Date"); 
    353                        break
    354                    }
     
    355                }
     
    356                xml.Close(); 
    357                sm.Close(); 
    358            }
     
    359            catch (WebException ex) 
    360            
    361                MeBox(ex.Message); 
    362            }
     
    363            return LastUpdateTime; 
    364        }
     
    365    }
     
    366}

    367
  • 相关阅读:
    php安全模式笔记
    ./configure,make,make install的作用(转)
    composer自动载入类库的方式
    Specified key was too long; max key length is 1000 bytes
    海量数据中找出前k大数(topk问题)
    斐波那契数列n项的值。(递归和非递归算法Golang实现)
    基于Docker和Golang搭建Web服务器
    Nginx简单介绍以及linux下使用Nginx进行负载均衡的搭建
    php实现商城秒杀
    一致性hash (PHP)
  • 原文地址:https://www.cnblogs.com/downcom/p/1264189.html
Copyright © 2011-2022 走看看