用IIS或者是Tomcat搭建一个Web服务器,因为没有涉及到动态页面,所以用什么服务器无所谓,网上有太多资料,这里不再赘述。

废话不多说,直接上代码。

HttpHelper, 访问网页,下载文件等

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO; namespace AutoUpdate
{
class HttpHelper
{ //以GET方式抓取远程页面内容
public static string Get_Http(string tUrl)
{
string strResult;
try
{
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl);
hwr.Timeout = ;
HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
Stream myStream = hwrs.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.Default);
StringBuilder sb = new StringBuilder();
while (- != sr.Peek())
{
sb.Append(sr.ReadLine() + "\r\n");
}
strResult = sb.ToString();
hwrs.Close();
}
catch (Exception ee)
{
strResult = ee.Message;
}
return strResult;
}
//以POST方式抓取远程页面内容
//postData为参数列表
public static string Post_Http(string url, string postData, string encodeType)
{
string strResult = null;
try
{
Encoding encoding = Encoding.GetEncoding(encodeType);
byte[] POST = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = POST.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(POST, , POST.Length); //设置POST
newStream.Close();
// 获取结果数据
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
strResult = reader.ReadToEnd();
}
catch (Exception ex)
{
strResult = ex.Message;
}
return strResult;
} /// <summary>
/// c#,.net 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
///
/// <param name="Filename">下载后的存放地址</param>
/// <param name="Prog">用于显示的进度条</param>
///
public static void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1,string description)
{
float percent = ;
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (prog != null)
{
prog.Maximum = (int)totalBytes;
}
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = st.Read(by, , (int)by.Length);
while (osize > )
{
totalDownloadedByte = osize + totalDownloadedByte;
System.Windows.Forms.Application.DoEvents();
so.Write(by, , osize);
if (prog != null)
{
prog.Value = (int)totalDownloadedByte;
}
osize = st.Read(by, , (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * ;
label1.Text = description + "下载进度" + percent.ToString() + "%";
label1.Refresh();
System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
System.Threading.Thread.Sleep();
}
so.Close();
st.Close();
}
catch (System.Exception)
{
throw;
}
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后的存放地址</param>
//public static void DownloadFile(string URL, string filename)
// {
// DownloadFile(URL, filename, null,null);
// }
}
}

update.txt (JSON格式的文件,版本号,更新的文件等,网络和本地比对)

{
"Version":"",
"Server":"http://192.168.242.12:9001/",
"Description":"修正一些Bug",
"File":"Checkup.exe",
"UpdateTime":"2016-06-20 12:02:05",
"UpdateFiles":[
{"File":"xx.txt"},
{"File":"Checkup.exe"}
]
}

AutoUpdate.cs (界面、自动更新程序。需加入Newtonsoft.Json引用,网上下载直接加入引用就可以了)

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms; namespace AutoUpdate
{
public partial class AutoUpdate : Form
{
private String UpdateServer ;
SynchronizationContext _syncContext = null;
public AutoUpdate()
{
InitializeComponent();
_syncContext = SynchronizationContext.Current;
}
private void dowm() {
_syncContext.Post(downFile,new object());
} private void AutoUpdate_Load(object sender, EventArgs e)
{ UpdateServer = ConfigurationManager.AppSettings["UpdateServer"];
int vs = isUpdate();
if (vs == )
{
label1.Text = "正在下载更新文件,请稍候。。。";
try
{
new Thread(new ThreadStart(dowm)).Start(); }
catch (Exception ee)
{
MessageBox.Show("下载异常:" + ee.Message);
}
}
else if (vs > )
{
label1.Text = "正在下载更新文件,请稍候。。。";
try
{
new Thread(new ThreadStart(dowm)).Start();
//Thread.Sleep(500);
//downFile();
}
catch (Exception ee)
{
MessageBox.Show("下载异常:" + ee.Message);
}
}
else {
Console.WriteLine("小于或等于0");
this.Close();
Process.Start("Checkup.exe");
}
}
private int isUpdate()
{
//Version ApplicationVersion = new Version(Application.ProductVersion);
//int version = ApplicationVersion.Major;
string[] lines = System.IO.File.ReadAllLines("update.txt");
String updateFile = "";
foreach (string line in lines)
{
updateFile = updateFile+"\t" + line;
}
JObject updateJson =JObject.Parse(updateFile);
int version = Int32.Parse(updateJson["Version"].ToString());
JObject udJson;
try
{
udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer));
}
catch (Exception ee) {
Console.WriteLine(ee.Message);
return -;
}
if (udJson != null)
{
int serverVersion = Int32.Parse(udJson["Version"].ToString());
return serverVersion - version;
// if (serverVersion-version)
// {
// Console.WriteLine("版本号不一致");
// return true;
// }
// else {
// Console.WriteLine("版本一致");
// return false;
// }
}
else {
return -;
}
}
private void downFile1(object state) {
JObject udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer));
JArray ja = (JArray)JsonConvert.DeserializeObject(udJson["UpdateFiles"].ToString());
HttpHelper.DownloadFile(udJson["Server"].ToString() + ja[ja.Count-]["File"].ToString(), ja[ja.Count - ]["File"].ToString(),progressBar1,label1, udJson["Description"].ToString());
HttpHelper.DownloadFile(UpdateServer, "update.txt", progressBar1, label1, udJson["Description"].ToString());
Start();
}
private void downFile(object state)
{
JObject udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer));
JArray ja = (JArray)JsonConvert.DeserializeObject(udJson["UpdateFiles"].ToString());
for (int i = ; i < ja.Count; i++)
{
HttpHelper.DownloadFile(udJson["Server"].ToString() + ja[i]["File"].ToString(), ja[i]["File"].ToString(), progressBar1, label1, udJson["Description"].ToString());
}
HttpHelper.DownloadFile(UpdateServer, "update.txt", progressBar1, label1, udJson["Description"].ToString());
Start();
}
private void Start() {
Process.Start("Checkup.exe");
this.Hide();
this.Close();
}
}
}

app.config(更新地址配置文件)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="UpdateServer" value="http://192.168.242.12:9001/update.txt"></add>
</appSettings>
</configuration>

需在相应的web服务器下放入版本号大于本地文件的update.txt。还有需要更新的文件。以及修改update.txt中UpdateFiles.

至此大功搞成。
源代码:http://download.csdn.net/detail/zuxuguang/9567453

winform、C# 自动更新的更多相关文章

  1. winform实现自动更新并动态调用form实现

    winform实现自动更新并动态调用form实现 标签: winform作业dllbytenull服务器 2008-08-04 17:36 1102人阅读 评论(0) 收藏 举报  分类: c#200 ...

  2. WinForm通用自动更新器AutoUpdater项目实战

    一.项目背景介绍 最近单位开发一个项目,其中需要用到自动升级功能.因为自动升级是一个比较常用的功能,可能会在很多程序中用到,于是,我就想写一个自动升级的组件,在应用程序中,只需要引用这个自动升级组件, ...

  3. 使用 advanced installer 为 winform 做自动更新

    原文:使用 advanced installer 为 winform 做自动更新 advanced installer 是一款打包程序,基于 windows installer 并扩展了一些功能,比如 ...

  4. C#[WinForm]实现自动更新

    C#[WinForm]实现自动更新 winform程序相对web程序而言,功能更强大,编程更方便,但软件更新却相当麻烦,要到客户端一台一台地升级,面对这个实际问题,在最近的一个小项目中,本人设计了一个 ...

  5. WinForm通用自动更新AutoUpdater项目实战

    目前我们做的上位机项目还是以Winform为主,在实际应用过程中,可能还会出现一些细节的修改.对于这种情况,如果上位机带有自动更新功能,我们只需要将更新后的应用程序打包放在指定的路径下,可以让用户自己 ...

  6. .net winform软件自动更新

    转载自 http://dotnet.chinaitlab.com/DotNetFramework/914178.html 关于.NET windows软件实现自动更新,本人今天写了一个DEMO,供大家 ...

  7. C#Winform实现自动更新

    服务端: [WebMethod] public string GetNewService(string version) { //通过版本号进行比较 if (version == "v1.0 ...

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

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

  9. winform 通用自动更新程序

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

  10. winform版本自动更新

    我们在使用软件的时候经常会遇到升级版本,这也是Winform程序的一个功能,今天就大概说下我是怎么实现的吧(代码有点不完美有小BUG,后面再说) 先说下我的思路:首先在打开程序的时候去拿到我之前在网站 ...

随机推荐

  1. nginx域名隐性(地址栏域名不变)跳转

    1.完全url的域名隐性跳转 server_name a.b.com location / { proxy_pass http://x.y.com; } 效果:浏览器地址栏中输入a.b.com域名不变 ...

  2. 使用BOOTICE 恢复系统启动项

    使用BOOTICE 恢复系统启动项 我在安装deepin 系统的时候,经常遇到重启进不去系统,每次重启都会进入windows 系统,这让我感到特别头疼,试了好多次都不成功,有些情况是,成功后再次重启又 ...

  3. ubuntu14.04下安装ngnix,mediawiki,nodebb,everything,gitlab

    本周折腾了以下几个东西,mediawiki(维基),nodebb(论坛),gitlab(私有git服务器). 本来的目的是搭建一个wiki,选用了mediawiki后,使用apache搭建好了. 搭论 ...

  4. AnjularJS异步编程 Promise和$q

    Promise,是一种异步处理模式. js代码的函数嵌套会使得程序执行异步代码时很难调试.因为多重嵌套的函数无法确定何时触发回调. 如: funA(arg1,arg2,function(){ func ...

  5. Thinking in Java——笔记(12)

    Error Handling with Exceptions The ideal time to catch an error is at compile time, before you even ...

  6. AtomicBoolean运用

    AtomicBoolean运用 首先先看如下例子 private static class BarWorker implements Runnable { private static boolean ...

  7. c语言编程

    1.常量和变量:变量是一块内存空间,该内存空间有类型约束,该内存中存放的数据可变. 变量三要素:类型,名称,值.常量:常量的数据永远不变,a:自变量,b:符合常量,c:预定义常量. 2.运算符和返回类 ...

  8. [uva12170]Easy Climb

    还是挺难的一个题,看了书上的解析以后还是不会写,后来翻了代码仓库,发现lrj又用了一些玄学的优化技巧. #include <algorithm> #include <iostream ...

  9. Execel(导出新方法):

    #region 新方法 //var sbHtml = new StringBuilder(); //sbHtml.Append("<table border='1' cellspaci ...

  10. Cocoa Touch事件处理流程--响应者链

    Cocoa Touch事件处理流程--响应者链 作者:wangzz 原文地址:http://blog.csdn.net/wzzvictory/article/details/9264335 转载请注明 ...