最近一直忙于一个项目的最后测试.虽然很忙,但是还抽出空来写一篇文章.呵呵,
由于winfrom的项目.客户不喜欢使用微软的click once 来安装程序和更新程序,所以需要我们自己开发一个更新程序.
事实上更新程序的原理很简单的,只是简单的copy文件而也..换掉一些旧的dll文件.下面是一些源程序:
如果你是局域网的,并且你可以访问服务器上的文件夹的时候,就可以用File.Copy来实现文件的Copy.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using System.Net;
using System.IO;
using System.Data.SqlClient;
namespace iTraz.Updater
{
public partial class frmUpdater : Form
{
bool flag = false;//indicate whether the version has changed
public frmUpdater()
{
InitializeComponent();
}
private void frmUpdater_Load(object sender, EventArgs e)
{
try
{
updateDll();
callMainForm();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void callMainForm()
{
try
{
//start other exe after updating dll.
string fileName = System.Environment.CurrentDirectory + "//" + "Start.exe";
System.Diagnostics.Process.Start(fileName);
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void updateDll()
{
try
{
//server path..
string url = "//192.28.1.12//updatePath//test.dll";
//local path.
// Assembly asm = Assembly.GetExecutingAssembly();
string str = Assembly.GetExecutingAssembly().GetName().CodeBase;
if (str.ToLower().IndexOf("file:///") >= 0)
{
str = str.Substring(8, str.Length - 8);
}
string fileName = System.IO.Path.GetDirectoryName(str)+"//"+"test.dll";
//here can add extra code for comparing two files's update date..if they are same..no need update.
if(File.Exist(fileName))
File.Delete(fileName);
File.Copy(url,fileName,true);
}
catch
{
MessageBox.Show("can not access update path on server.");
}
}
}
}
当然这种File.Copy需要你有一定的权限.
如果你没有足够的权权限,我们可以改写updetadll这个方法
try
{
//server path..
string url = "//192.28.1.12//updatePath//test.dll";
//local path.
// Assembly asm = Assembly.GetExecutingAssembly();
string str = Assembly.GetExecutingAssembly().GetName().CodeBase;
if (str.ToLower().IndexOf("file:///") >= 0)
{
str = str.Substring(8, str.Length - 8);
}
string fileName = System.IO.Path.GetDirectoryName(str)+"//"+"test.dll";
//use http for updating.
WebRequest request = WebRequest.Create(url);
WebResponse response= request .GetResponse();
Stream rec= response.GetResponseStream();
//delete all old files
File.Delete(fileName);
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
try
{
List<byte> lstByte = new List<byte>();
while (true)
{
//read data from new files
int i = rec.ReadByte();
if (i == -1)
{
break;
}
fs.WriteByte(Convert.ToByte(i));
}
}
finally
{
if (fs != null)
fs.Close();
response.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
request.DefaultWebProxy = null;
}
其实很简单吧.如果用clickOnce 的话,我想会更简单的哦,呵呵!没办法