用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

最新文章

  1. sphinx全文检索 安装配置和使用
  2. CSS3弹力球
  3. LayoutInflater中四种类型inflate方法的介绍
  4. Oracle计算时间函数(numtodsinterval、numtoyminterval)
  5. js 验证表单 js提交验证类
  6. Android入门随记
  7. Arduino 板子 COM 接口找不到设备
  8. 我的Python成长之路---第三天---Python基础(11)---2016年1月16日(雾霾)
  9. AMS常见问题
  10. day14- 面向对象基础(一)
  11. Java自学笔记
  12. git教程:远程仓库
  13. python数据分析及展示(三)
  14. 使用maven对项目进行junit的单元测试
  15. [UE4]键盘鼠标输入事件
  16. 2017-11-29 由runnable说起Android中的子线程和主线程
  17. Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location
  18. BestCoder Round #12 War(计算几何)
  19. ECS 游戏架构 实现
  20. Android api level对照表

热门文章

  1. 02.JavaScript基础上
  2. *HDU2852 树状数组(求第K小的数)
  3. IOS ReactiveCocoa
  4. Mysql5.7修改默认密码
  5. 函数Curry化
  6. laravel Input Cokkie 的各种方法 超实用!!!
  7. 手机版本高于xcode,xcode的快速升级
  8. 群晖SVN Server远程访问
  9. Ubantu Linux 环境下编译c++程序
  10. jira操作