客户端程序自动更新
客户端程序更新,通常做法是做一个更新程序通过TCP/IP,HTTP,FTP协议指定路径,下载文件与本地文件进行比对。比对成功之后下载压缩包并解压替换本地程序。
本文暂不比对版本,直接从FTP目录下载文件替换本地程序。
本次采用FTP模式
FtpHelper.cs
static public class FtpHelper
{
//基本设置
static private string path = @"ftp://" + Helper.GetAppConfig("obj") + "/"; //目标路径
static private string ftpip = Helper.GetAppConfig("obj"); //ftp IP地址
static private string username = Helper.GetAppConfig("username"); //ftp用户名
static private string password = Helper.GetAppConfig("password"); //ftp密码
//获取ftp上面的文件和文件夹
public static string[] GetFileList(string dir)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.UseBinary = true;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
Console.WriteLine(line);
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
Console.WriteLine("获取ftp上面的文件和文件夹:" + ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// 获取文件大小
/// </summary>
/// <param name="file">ip服务器下的相对路径</param>
/// <returns>文件大小</returns>
public static int GetFileSize(string file,string Dir)
{
StringBuilder result = new StringBuilder();
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path+ "\\" + Dir + "\\" + file));
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
request.Method = WebRequestMethods.Ftp.GetFileSize;
int dataLength = (int)request.GetResponse().ContentLength;
return dataLength;
}
catch (Exception ex)
{
Console.WriteLine("获取文件大小出错:" + ex.Message);
return -1;
}
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filePath">原路径(绝对路径)包括文件名</param>
/// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
public static void FileUpLoad(