Downloader调用WCF服务返回文件

时间:2022-03-29 08:52:56

Generator

 using System;
using System.Collections.Generic;
using System.IO; namespace Downloader
{
public class Generator : StatusProcess
{
private readonly string _appPath = AppDomain.CurrentDomain.BaseDirectory;
protected void GenerateFileList(string dir, List<FileEntity> fileEntities)
{
var files = Directory.GetFiles(dir);
foreach (var tem in files)
{
var fileInfo = new FileInfo(tem);
var file = new FileEntity()
{
FileName = tem.Replace(_appPath, "").Replace("\\", "\\\\"),
LastUpdate = fileInfo.LastWriteTime.ToString("yyyyMMddHHmmss")
};
fileEntities.Add(file);
} var directories = Directory.GetDirectories(dir);
foreach (var directory in directories)
{
GenerateFileList(directory, fileEntities);
}
} public void GenerateFileList()
{
var filelist = new FileListEntity() { FileCode = Guid.NewGuid().ToString().ToUpper().Replace("-", "") };
GenerateFileList(_appPath, filelist.FileEntities);
filelist.SerializeConfig(Path.Combine(_appPath, "filelist.xml"));
} public void DownloadFileList(string path, string url, string customerCode, string token, string mac)
{
#region 请求filelist.xml var client = new RestClient
{
EndPoint = url,
Method = HttpVerb.Post
}; const string curfilename = "curfilelist.xml";
const string newfilename = "filelist.xml";
InvokeStatus(string.Format("正在请求{0}", newfilename));
string filename = newfilename;
string postdata =
string.Format("\"CustomerCode\":\"{0}\",\"Token\":\"{1}\",\"Mac\":\"{2}\",\"Filename\":\"{3}\"",
customerCode, token, mac, filename);
var makeRequest = client.MakeRequest("", postdata); #endregion if (makeRequest.Length > )
{
InvokeStatus(string.Format("正在保存{0}", newfilename)); #region 正在保存filelist.xml filename = Path.Combine(path, filename);
var directoryName = Path.GetDirectoryName(filename);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
using (var file = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
{
file.Write(makeRequest, , makeRequest.Length);
} #endregion #region 判断是否需要更新 var curfileListEntity = new FileListEntity();
var fileListEntity = filename.DeserializeConfig<FileListEntity>(); if (File.Exists(Path.Combine(path, curfilename)))
{
curfileListEntity = Path.Combine(path, curfilename).DeserializeConfig<FileListEntity>();
if (fileListEntity.FileCode == curfileListEntity.FileCode)
{
File.Delete(Path.Combine(path, newfilename));
InvokeStatus("不需要更新");
return;
}
} #endregion #region 更新文件列表 foreach (var fileEntity in fileListEntity.FileEntities)
{
var find = curfileListEntity.FileEntities.Find(entity => entity.FileName == fileEntity.FileName); if (find != null && fileEntity.LastUpdate == find.LastUpdate)
{
continue;
}
filename = fileEntity.FileName;
InvokeStatus("正在更新" + filename);
postdata = string.Format("\"CustomerCode\":\"{0}\",\"Token\":\"{1}\",\"Mac\":\"{2}\",\"Filename\":\"{3}\"", customerCode, token, mac, filename);
makeRequest = client.MakeRequest("", postdata);
if (makeRequest.Length > )
{
InvokeStatus("正在保存" + filename);
filename = Path.Combine(path, filename);
directoryName = Path.GetDirectoryName(filename);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
using (var file = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
{
file.Write(makeRequest, , makeRequest.Length);
}
}
} #endregion File.Delete(Path.Combine(path, curfilename));
File.Move(Path.Combine(path, newfilename), Path.Combine(path, curfilename));
InvokeStatus("update ok");
}
else
{
InvokeStatus("请求更新失败,请确认配置信息");
}
}
} public class FileEntity
{
public string LastUpdate { get; set; }
public string FileName { get; set; }
} public class FileListEntity
{
private List<FileEntity> _fileEntities = new List<FileEntity>();
public string FileCode { get; set; } public List<FileEntity> FileEntities
{
get { return _fileEntities; }
set { _fileEntities = value; }
}
}
}

StatusProcess

 /* Jonney Create 2015-3-22 */
using System.Diagnostics;
using System.Windows.Forms; namespace Downloader
{
public delegate void DownloadStatusHandler(string status); public class StatusProcess
{
/// <summary>
/// 下载状态事件,状态改变都会触发
/// </summary>
public event DownloadStatusHandler DownloadStatus; protected readonly Stopwatch Stopwatch; public StatusProcess()
{
Stopwatch = new Stopwatch();
} /// <summary>
/// 如果DownloadStatus事件被注册,都会被执行
/// </summary>
/// <param name="status"></param>
protected void InvokeStatus(string status)
{
if (DownloadStatus != null)
{
DownloadStatus.Invoke(status);
Application.DoEvents();
}
}
} }

Downloader

         private void btnUpdater_Click(object sender, EventArgs e)
{
var thread = new Thread(DownloadFilelist) {IsBackground = true};
thread.Start();
} private void DownloadFilelist()
{
try
{
SetEnable(false);
const string cfg = "CustomerInfo.xml";
var generator = new Generator();
generator.DownloadStatus += generator_DownloadStatus; string file = Path.Combine(Application.StartupPath, cfg);
if (!File.Exists(file))
{
generator_DownloadStatus(string.Format("配置信息{0}损坏", cfg));
return;
}
var customerInfo = file.DeserializeConfig<CustomerInfo>();
if (customerInfo == null)
{
generator_DownloadStatus(string.Format("配置信息{0}损坏", cfg));
return;
} var mac = GetMacString();
customerInfo.Mac = mac[];
generator.DownloadFileList(Application.StartupPath
, customerInfo.ServerUrl
, customerInfo.CustomerCode
, customerInfo.Token
, customerInfo.Mac); this.Invoke(new Action(Boot));
}
catch (Exception err)
{
generator_DownloadStatus(string.Format("{0}", err.Message));
}
finally
{
/*SetEnable(true);*/
}
} private void SetEnable(bool isEnable)
{
this.Invoke(new Action(() =>
{
btnClose.Enabled = isEnable;
btnUpdater.Enabled = isEnable;
}));
} private void generator_DownloadStatus(string status)
{
this.Invoke(new Action(() =>
{
label1.Text = status;
Application.DoEvents();
}));
} public string[] GetMacString()
{
string strMac = "";
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
strMac += ni.GetPhysicalAddress() + "|";
}
}
return strMac.Split('|'); }