首页 > 代码库 > C/S端程序更新功能

C/S端程序更新功能

---创建一个用来更新的程序

---打开页面时进行更新

--App.config配置文件的信息

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>

  <appSettings>
    <!--本地版本号-->
    <add key="Local_Version" value="http://www.mamicode.com/1"/>//记录要更新程序的版本号

    <!--服务器版本请求URL-->
    <add key="ServerVersionUrl" value="http://112.74.26.247:808/UpdateServer/GetAssistVersion"/>//获取最新的程序版本号
    <!--服务器更新文件下载URL-->
    <add key="ServerUpdateFileUrl" value="http://112.74.26.247:808/UpdateServer/GetAssistUpdateFile"/>//下载最新的程序

  </appSettings>
</configuration>

 

private void Form1_Load(object sender, EventArgs e)
{
  try
  {
    //定位配置文件
    System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", Application.StartupPath + "\\GS.Update.exe.config");//"\\GS.Update.exe.config");//
    //获取本地版本号
    string local_Ver = ConfigurationManager.AppSettings["Local_Version"];
    //获取服务器版本请求URL
    string ServerVerUrl = ConfigurationManager.AppSettings["ServerVersionUrl"];
    //获取服务器版本信息
    string serverVerTag = GetServerVer(ServerVerUrl, local_Ver);

    //有新版本
    if (serverVerTag.Equals("old", StringComparison.OrdinalIgnoreCase))
    {
      //没有新版本,直接启动程序
      ToProcess("GS.Client.exe");
      Application.Exit();
    }
    else if (serverVerTag.Equals("invalid", StringComparison.OrdinalIgnoreCase))
    {
      MessageBox.Show("服务器配置不正确!");
      Application.Exit();
    }
    else
    {

      //获取服务器更新文件下载URL
      string serverVerUrl = ConfigurationManager.AppSettings["ServerUpdateFileUrl"];
      string savePath = "update.zip";//更新文件名
      //下载更新文件
      DownLoadUpdate(serverVerUrl, savePath);
      //当前程序目录
      string currentPath = Application.StartupPath + "\\";
      //解压文件
      UnZipFile(currentPath + savePath, currentPath);
      //删除压缩文件
      File.Delete(currentPath + savePath);

      //更新完成修改本地XML版本号
      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      config.AppSettings.Settings["Local_Version"].Value = http://www.mamicode.com/serverVerTag;//修改本地配置文件版本信息
      //保存配置文件
      config.Save();
      ToProcess("GS.Client.exe");

      //Application.Exit();
    }
  }
  catch (Exception ex)
  {
    //获取主程序路径
    MessageBox.Show(ex.Message);
    ToProcess("GS.Client.exe");
  }
  finally
  {
    Application.Exit();
  }
}


/// <summary>
/// 调用程序
/// </summary>
/// <param name="filePath"></param>
private void ToProcess(string filePath)
{
  Process pro = new Process();
  pro.StartInfo.UseShellExecute = true;
  pro.StartInfo.FileName = filePath;
  pro.StartInfo.CreateNoWindow = true;
  pro.Start();
}

/// <summary>
/// 获取服务器版本号
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string GetServerVer(string url, string localVer)
{
  string requestUrl = url + "?ClientVersion=" + localVer;
  //创建请求对象
  HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
  webRequest.KeepAlive = false;
  webRequest.Method = "GET";
  webRequest.Timeout = 10000;
  //发送请求
  HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
  return sr.ReadToEnd().Trim();
}

/// <summary>
/// 下载文件
/// </summary>
/// <param name="downloadUrl"></param>
/// <param name="savePath"></param>
private void DownLoadUpdate(string downloadUrl, string savePath)
{
  WebClient webclient = new WebClient();
  webclient.DownloadFile(new Uri(downloadUrl), savePath);
}

/// <summary>
/// 解压更新文件,并覆盖原文件
/// </summary>
/// <param name="zipFilePath">解压更新文件路径</param>
/// <param name="savePath">覆盖原文件路径</param>
private void UnZipFile(string zipFilePath, string savePath)
{
  if (!File.Exists(zipFilePath))
  {
    throw new Exception("更新文件不存在!");
  }

  using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
  {

    ZipEntry theEntry;
    while ((theEntry = s.GetNextEntry()) != null)
    {

      string directoryName = Path.GetDirectoryName(theEntry.Name);
      string fileName = Path.GetFileName(theEntry.Name);

      // create directory
      if (directoryName.Length > 0)
      {
        Directory.CreateDirectory(savePath + directoryName);
      }
      if (!directoryName.EndsWith("\\"))
      {
        directoryName += "\\";
      }

      if (fileName != String.Empty)
      {
        using (FileStream streamWriter = File.Create(savePath + directoryName + fileName))
        {

          int size = 2048;
          byte[] data = http://www.mamicode.com/new byte[2048];
          while (true)
          {
            size = s.Read(data, 0, data.Length);
            if (size > 0)
            {
              streamWriter.Write(data, 0, size);
            }
            else
            {
              break;
            }
          }
        }
      }
    }
  }
}

 

 

 

 

--Web.config配置文件的信息
<configuration>
  <appSettings>
    <!--更新目录路径-->
    <add key="GS-Path-Assist" value="http://www.mamicode.com/D://Update//update.zip"/>//记录更新文件所在的路径
    <!--更新版本号-->
    <add key="GS-Version" value="http://www.mamicode.com/D://Update//"/>//记录更新文件版本号
  </appSettings>

</configuration>

/// <summary>
/// 获取是否有新版本号
/// </summary>
/// <returns></returns>
public ActionResult GetAssistVersion()
{
  //客户端版本号
  string clientVer = Request.QueryString["ClientVersion"];
  int c_Ver;
  int.TryParse(clientVer, out c_Ver);
  //服务器端版本号
  int s_Ver;
  int.TryParse(ConfigurationManager.AppSettings["GS-Version"], out s_Ver);

  //判断版本号,
  if (c_Ver < s_Ver)
  {
    return Content(s_Ver.ToString());
  }
  else
  {
    return Content("old");
  }

}

/// <summary>
/// 获取更新文件
/// </summary>
/// <returns></returns>
public ActionResult GetAssistUpdateFile()
{

  //更新文件路径
  string path = ConfigurationManager.AppSettings["GS-Path-Assist"];
  return File(path, "application/x-zip-compressed");
}

C/S端程序更新功能