用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. PHP 实现数学问题:组合

    需求: 有一个数组 ['a', 'b', 'c', 'cd'] 需要从数组中取出任意 m 个不重复的元素,列出所有的可能性(也不需要出现重复的组合例如['a', 'b' ,'c'] 和 ['a', ' ...

  2. win7下利用VM8安装CentOS6.3配置静态IP上网

    1 环境 宿主主机64位win7,利用VM8安装的64位CentOS6.3,64位的.在VM中配置CentOS的IP为静态,可上互联网.具体配置过程如下. 2 步骤 首先将VM的setting选项中, ...

  3. mongoperf

    官方文档 mongoperf is a utility to check disk I/O performance independently of MongoDB. It times tests o ...

  4. spring-amqp 动态创建queue、exchange、binding

    pom.xml <!-- mq 依赖 --> <dependency> <groupId>com.rabbitmq</groupId> <arti ...

  5. python Gunicorn

    1. 简介 Gunicorn(Green Unicorn)是给Unix用的WSGI HTTP 服务器,它与不同的web框架是非常兼容的.易安装.轻.速度快. 2. 示例代码1 def app(envi ...

  6. MVC中的数据注解和验证

    数据注解和验证 用户输入验证在客户端浏览器中需要执行验证逻辑. 在客户端也需要执行. 注解是一种通用机制, 可以用来向框架注入元数据, 同时, 框架不只驱动元数据的验证, 还可以在生成显示和编辑模型的 ...

  7. (转载)(收藏)Awk学习详细文档

    awk命令 本文索引 [隐藏] awk命令格式和选项 awk模式和操作 模式 操作 awk脚本基本结构 awk的工作原理 awk内置变量(预定义变量) 将外部变量值传递给awk awk运算与判断 算术 ...

  8. JMX

    一.为什么使用JMX,解决那些问题 举一个应用实例:在一个系统中常常会有一些配置信息,比如服务的IP地址,端口号什么的,那么如何来写这些代码呢? 写死在程序里,到要改变时就去改程序,然后再编译发布: ...

  9. 鸟哥linux私房菜基础篇

    1)注销:exit2)指令太长:命令太长的时候,可以使用反斜杠 (\) 来跳脱[Enter]符号,使挃令连续到下一行3)系统语言显示和设置命令:echo $LANG,显示当前系统语言:简体中文zh_C ...

  10. form上传文件2种方式

    示例1: 表单里有图片/文件的上传 <form enctype="multipart/form-data" method="post"> <i ...