using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.ComponentModel;
using HPSocketCS.Extended;
using System.Runtime.InteropServices;
namespace HPNetwork.TCPNetworkClient
{
///
/// TCP网络通信客户端
///
public class TCP_NetworkClient
{
public TCP_NetworkClient() {
}
#region 网络客户端程序处理代码
TCP_NetworkClient tFileClient=null;
///
/// 文件传送通道
///
public TCP_NetworkClient TFileClient
{
get {
if (this.tFileClient == null)
{
this.tFileClient = new TCP_NetworkClient();
}
return this.tFileClient;
}
}
private AppState appState = AppState.Stoped;
///
/// 当前网络状态
///
public AppState AppState
{
get { return appState; }
set { appState = value; }
}
// private delegate void ConnectUpdateUiDelegate();
// private delegate void SetAppStateDelegate(AppState state);
HPSocketCS.TcpPackClient client = new HPSocketCS.TcpPackClient();
///
/// 客户端连接
///
public HPSocketCS.TcpPackClient Client
{
get { return client; }
}
///
/// 连接服务器
///
/// ip
/// 端口
/// 是否异步连接
///
public bool ConnectionServer(string hostOrIP="", ushort port=0, bool isAsyncConn = false)
{
try
{
if (this.AppState == HPSocketCS.Extended.AppState.Started)
{
return true;
}
if (!this.isInitializesNetwork)
{
this.InitializesNetwork();
}
bool cAsyncConn = isAsyncConn;
// 写在这个位置是上面可能会异常
SetAppState(AppState.Starting);
// AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
SystemFileLogs.WriteLogs(string.Format("客户端开始连接... -> ({0}:{1})", hostOrIP, port));
if (client.Connetion(hostOrIP, port, cAsyncConn))
{
if (cAsyncConn == false)
{
SetAppState(AppState.Started);
}
// AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
SystemFileLogs.WriteLogs(string.Format("客户端连接OK -> ({0}:{1})", hostOrIP, port));
return true;
}
else
{
SetAppState(AppState.Stoped);
throw new Exception(string.Format("客户端连接出错 -> {0}({1})", client.ErrorMessage, client.ErrorCode));
}
}
catch (Exception ex)
{
SystemFileLogs.WriteLogs(string.Format("客户端连接失败-> ({0})", ex.Message));
}
return false;
}
///
/// 关闭客户端连接
///
///
public bool CloseConnected()
{
// 停止服务
SystemFileLogs.WriteLogs(string.Format("准备关闭客户端连接"));
if (this.AppState == HPSocketCS.Extended.AppState.Started)
{
if (client.Stop())
{
SetAppState(AppState.Stoped);
if (this.tFileClient != null && this.tFileClient.AppState == HPSocketCS.Extended.AppState.Started)
{
this.tFileClient.CloseConnected();
}
return true;
}
else
{
// AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
SystemFileLogs.WriteLogs(string.Format("关闭客户端连接失败-> {0}({1})", client.ErrorMessage, client.ErrorCode));
}
}
else {
return true;
}
return false;
}
bool isInitializesNetwork = false;
///
/// 网络服务是否已初始化
///
public bool IsInitializesNetwork
{
get { return isInitializesNetwork; }
set { isInitializesNetwork = value; }
}
///
/// 初始化网络
///
void InitializesNetwork()
{
try
{
// 设置client事件
client.OnPrepareConnect += new HPSocketCS.TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
client.OnConnect += new HPSocketCS.TcpClientEvent.OnConnectEventHandler(OnConnect);
client.OnSend += new HPSocketCS.TcpClientEvent.OnSendEventHandler(OnSend);
client.OnReceive += new HPSocketCS.TcpClientEvent.OnReceiveEventHandler(OnReceive);
client.OnClose += new HPSocketCS.TcpClientEvent.OnCloseEventHandler(OnClose);
// 设置包头标识,与对端设置保证一致性
client.PackHeaderFlag = 0x1ff;
// 设置最大封包大小
client.MaxPackSize = 0x2000 * 32;
client.SocketBufferSize = 512 * 1024;//client.MaxPackSize;
SystemFileLogs.WriteLogs("客户初始化网络成功");
SetAppState(AppState.Stoped);
this.isInitializesNetwork = true;
}
catch (Exception ex)
{
SetAppState(AppState.Error);
// AddMsg(ex.Message);
SystemFileLogs.WriteLogs("客户初始化网络时出错:" + ex.Message);
}
}
HPSocketCS.HandleResult OnPrepareConnect(HPSocketCS.TcpClient sender, uint socket)
{
return HPSocketCS.HandleResult.Ok;
}
HPSocketCS.HandleResult OnConnect(HPSocketCS.TcpClient sender)
{
// 已连接 到达一次
// 设置附加数据
string ip = "";
ushort port = 0;
if (sender.GetListenAddress(ref ip, ref port))
{
HPSocketCS.Extended.ClientInfo ci = new HPSocketCS.Extended.ClientInfo();
ci.ConnId = sender.ConnectionId;
ci.IpAddress = ip;
ci.Port = port;
sender.SetExtra(ci);
}
// 如果是异步联接,更新界面状态
// this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
// AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
SystemFileLogs.WriteLogs("已连接:" + ip + ":" + port.ToString());
return HPSocketCS.HandleResult.Ok;
}
HPSocketCS.HandleResult OnSend(HPSocketCS.TcpClient sender, byte[] bytes)
{
// 客户端发数据了
//AddMsg(string.Format(" > [{0},OnSend] ->数据发送成功 ({1} bytes)", sender.ConnectionId, bytes.Length));
return HPSocketCS.HandleResult.Ok;
}
HPSocketCS.HandleResult OnReceive(HPSocketCS.TcpClient sender, byte[] bytes)
{
// 数据到达了
try
{
//收到的数据
byte[] receiveBytes = new byte[0];
TcpHeadInfo header = sender.BytesToStruct(bytes);
try
{
DataType dType = (DataType)header.MsgDataType;
int headSize = Marshal.SizeOf(header);
TcpTailInfo tail = new TcpTailInfo();
if (header.IsTail)
{
//有附加尾数据时
int tailSize = Marshal.SizeOf(tail);
byte[] tailBytes = new byte[tailSize];
Array.ConstrainedCopy(bytes, bytes.Length - tailSize, tailBytes, 0, tailBytes.Length);
tail = sender.BytesToStruct(tailBytes);
receiveBytes = new byte[bytes.Length - headSize - tailSize];
Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
tailBytes = null;
}
else
{
// 因为没有附加尾数据,所以大小可以用length - objSize
receiveBytes = new byte[bytes.Length - headSize];
Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
}
ReceiveCacheBuffer recBuffer = sender.CCommonLibrary.GetReceiveCacheBuffer(header.TransportID);
if (recBuffer != null)
{
lock (recBuffer)
{
recBuffer.Length += receiveBytes.Length;
if (recBuffer.BackgroundWorker != null)
{
//总计数器
long sumCount = header.IntactSize;
if (dType == DataType.File)
{
sumCount = tail.FileSize;
}
//当前计数器
long currentCount = recBuffer.Length;
if (header.TransportEnd && tail.IsSendComplete)
{
currentCount = Convert.ToInt64(sumCount);
}
CommonLibrary.SetBackgroundWorker(sumCount, currentCount,"正在接收数据,请稍等...", recBuffer.BackgroundWorker);
}
}
}
//接收到的客户端发送来的数据
byte[] recbytes = null;
try
{
if (header.TransportStart && header.TransportEnd)
{
recbytes = receiveBytes;
receiveBytes = null;
}
else
{
ReceiveData rData = sender.CCommonLibrary.GetReceiveData(header);
if (rData == null)
{
rData = new ReceiveData();
sender.CCommonLibrary.AddReceiveData(rData);
}
rData.ReceiveRemoteClientInfo = header;
rData.ReceiveDataMstream.Write(receiveBytes, 0, receiveBytes.Length);
if (header.TransportEnd)
{
recbytes = rData.ReceiveDataMstream.ToArray();
sender.CCommonLibrary.RemoveReceiveDataData(rData);
}
}
if (recbytes != null)
{
recbytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(recbytes);
if (!header.IsTail && header.TransportEnd)
{
tail.IsSendComplete = true;
}
switch (dType)
{
case DataType.Text:
if (recBuffer != null)
{
if (!recBuffer.ReceiveComplete(recbytes,tail.IsSendComplete))
{
return HPSocketCS.HandleResult.Error;
}
}
break;
case DataType.File:
if (!sender.ReceiveDownloadFile(header, tail, recBuffer, recbytes))
{
return HPSocketCS.HandleResult.Error;
}
break;
case DataType.Serialization:
case DataType.SQLHelper:
if (recBuffer != null)
{
if (!recBuffer.ReceiveComplete(recbytes, tail.IsSendComplete))
{
return HPSocketCS.HandleResult.Error;
}
}
// break;
break;
case DataType.List:
break;
case DataType.Array:
break;
case DataType.None:
break;
}
}
}
finally
{
recbytes = null;
}
return HPSocketCS.HandleResult.Ok;
}
catch
{
sender.CCommonLibrary.RemoveServerToClientByteList(header.TransportID);
return HPSocketCS.HandleResult.Ignore;
}
}
catch (Exception ex)
{
SystemFileLogs.WriteLogs("接收数据时出错:" + ex.Message);
return HPSocketCS.HandleResult.Error;
}
finally
{
System.GC.Collect();
}
}
HPSocketCS.HandleResult OnClose(HPSocketCS.TcpClient sender, HPSocketCS.SocketOperation enOperation, int errorCode)
{
try
{
try
{
sender.CCommonLibrary.ClearAllInvalidResource();
}
catch { }
try
{
sender.CCommonLibrary.ClearAllServerToClientByteList();
}
catch { }
SetAppState(AppState.Stoped);
if (errorCode == 0)
{
// 连接关闭了
// AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
SystemFileLogs.WriteLogs("连接关闭了");
}
else if (enOperation == HPSocketCS.SocketOperation.Close)
{
SystemFileLogs.WriteLogs(string.Format(" 服务器已关闭连接> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
}
else
{
// 出错了
// AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
SystemFileLogs.WriteLogs(string.Format(" 连接出错了> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
}
// 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
// 生产环境请自己控制
// this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
}
catch { }
return HPSocketCS.HandleResult.Ok;
}
///
/// 设置程序状态
///
///
void SetAppState(AppState state)
{
appState = state;
}
///
/// 上传头像
///
/// 要上传的头像路径
///
///
public string UploadAvatarToServer(string fileFullName, BackgroundWorker backgroundWorker = null)
{
return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, fileFullName, System.IO.Path.GetFileName(fileFullName), backgroundWorker);
}
///
/// 上传文件
///
/// 要上传的文件路径
/// 上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”
///
///
public string UploadFileToServer(string fileFullName, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
{
return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, fileFullName, toServerFileFullName, backgroundWorker);
}
///
/// 上传图片
///
/// 要上传的图片
/// 上传的图片格式
/// 上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”
/// 上传后是否释放图片资源
///
///
public string UploadFileToServer(System.Drawing.Image img, System.Drawing.Imaging.ImageFormat imgFormat, string toServerFileFullName, BackgroundWorker backgroundWorker = null, bool isDisposeImg = true)
{
MemoryStream memoryMS = new MemoryStream();
img.Save(memoryMS, imgFormat);
if (isDisposeImg)
{
img.Dispose();
}
return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
}
///
/// 上传内存流
///
/// 要上传的内存流
/// 上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”
/// 上传后是否释放图片资源
///
///
public string UploadFileToServer(MemoryStream memoryMS, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
{
return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
}
///
/// 获取指定服务器端文件的信息
///
/// 为你向服务器请求的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”
///
public ServerFileInfo GetServerFileInfo(string sFileName)
{
ServerFileInfo sFileInfo = new ServerFileInfo();
if (this.AppState == HPSocketCS.Extended.AppState.Started)
{
try
{
// sFileInfo = new ServerFileInfo(sendFileProtocol.Content);
}
catch { sFileInfo.GetMsg = "连接已断开,请检查网络环境是否正常..."; }
}
return sFileInfo;
}
///
/// 下载头像
///
///
/// 头像下载后保存的位置
/// 头像图片名(带扩展名)
///
public string DownloadAvatar(string saveFileFullName, string fileName, BackgroundWorker backgroundWorker = null)
{
return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, fileName, fileName, backgroundWorker);
}
///
/// 下载头像
///
///
/// 保存到指定的内存流中
/// 头像图片名(带扩展名)
///
public string DownloadAvatar(MemoryStream memoryMS, string fileName, BackgroundWorker backgroundWorker = null)
{
return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
}
///
/// 下载头像
///
/// 返回下载的图片
/// 头像图片名(带扩展名)
///
///
public string DownloadAvatar(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
{
try
{
MemoryStream ImageMS = new MemoryStream();
string retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
try
{
resultBitmap = new System.Drawing.Bitmap(ImageMS);
}
catch
{
retMsg = "下载失败,头像生成时失败";
}
ImageMS.Close();
ImageMS.Dispose();
return retMsg;
}
catch (Exception ex)
{
return "下载失败:" + ex.ToString();
}
}
///
/// 下载文件
///
/// 下载后保存的位置
/// 为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”
///
///
public string DownloadFile(string saveFileFullName, string serverFileFullName, BackgroundWorker backgroundWorker = null)
{
return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, saveFileFullName, serverFileFullName, backgroundWorker);
}
///
/// 下载文件
///
/// 保存到指定的内存流中
/// 为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”
///
///
public string DownloadFile(MemoryStream memoryMS, string serverFileFullName, BackgroundWorker backgroundWorker = null)
{
return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", serverFileFullName, backgroundWorker);
}
///
/// 下载图像
///
///
/// 返回下载的图片
/// 要下载的图片路径,以服务器程序的根目录定位 如“UpdateTemp\\test.jpg”
///
public string DownloadBitmap(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
{
try
{
string retMsg = "";
if (LYFZ.WinAPI.CustomPublicMethod.ExistsImgage(fileName))
{
MemoryStream ImageMS = new MemoryStream();
retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", fileName, backgroundWorker);
if (retMsg.Contains("成功"))
{
try
{
resultBitmap = new System.Drawing.Bitmap(ImageMS);
}
catch
{
retMsg = "下载失败,图像生成失败";
}
}
else
{
if (retMsg.Trim() == "")
{
retMsg = "下载失败,请重试";
}
}
ImageMS.Close();
ImageMS.Dispose();
}
else
{
retMsg = "您请求下载的文件不是图片,不能下载";
}
return retMsg;
}
catch (Exception ex)
{
return "下载失败:" + ex.ToString();
}
}
///
/// 向服务器上传文件
///
/// 上传命令
/// 上传的文件全路径
/// 上传到服务器上的目录路径 以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”
/// 参数
///
/// 如果是分店是否自动上传文件到总店服务器
///
public string SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, string fileFullName = "", string toServerFileFullName = "", BackgroundWorker backgroundWorker = null, MemoryStream memoryMS = null)
{
string tempMsg = "";
string fileName = toServerFileFullName;
bool ret = false;
TCP_NetworkClient myUploadClient = this.TFileClient;
if (this.TFileClient.AppState != HPSocketCS.Extended.AppState.Started)
{
this.TFileClient.ConnectionServer();
}
if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
{
//如果是上传头像时设置头像路径
toServerFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(toServerFileFullName);
}
if (myUploadClient.AppState == HPSocketCS.Extended.AppState.Started)
{
ServerFileInfo downloadFileInfo = myUploadClient.GetServerFileInfo(toServerFileFullName);
bool isUpload = true;//是否需要上传文件 用于判断要上传的文件是否在服务器上存在,如果存在就不上传
if (downloadFileInfo.IsExists)
{
if (downloadFileInfo.FileMd5.Trim().Length > 0)
{
if (memoryMS == null && fileFullName.Trim().Length > 0)
{
if (System.IO.File.Exists(fileFullName.Trim()))
{
FileInfo fi = new FileInfo(fileFullName.Trim());
if (fi.Length < HPSocketCS.Sdk.FileMD5VerifySize)
{
string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(fileFullName.Trim());
if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
{
isUpload = false;
}
}
}
}
else if (memoryMS != null)
{
if (downloadFileInfo.FileMd5.Trim().Length > 0)
{
memoryMS.Position = 0;
byte[] bytes = new byte[memoryMS.Length];
memoryMS.Read(bytes, 0, bytes.Length);
string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(bytes);
Array.Clear(bytes, 0, bytes.Length);
bytes = null;
if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
{
isUpload = false;
}
}
}
}
}
if (isUpload)
{
if (fileFullName.Trim().Length > 0 && System.IO.File.Exists(fileFullName.Trim()) && memoryMS == null)
{
ret = myUploadClient.Client.UploadFiles(fileFullName.Trim(), toServerFileFullName, backgroundWorker);
}
else if (memoryMS != null)
{
ret = myUploadClient.Client.UploadMemoryStream(memoryMS, toServerFileFullName, backgroundWorker);
}
else
{
return "要上传的文件不存在:" + fileFullName;
}
}
else
{
ret = true;
}
}
else
{
return "网络连接失败,请检查网络环境";
}
if (ret)
{
tempMsg = "上传成功";
}
else
{
tempMsg = "上传失败";
}
return tempMsg;
}
///
/// 临时缓存文件目录
///
static string TemporaryCachefilesPath = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + "Temp\\TemporaryCachefiles\\";
// static bool isFileServerIng = false;
///
/// 从服务器下载文件
///
///
/// 下载命令
/// 下载后要保存的文件全路
/// 为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”
///
/// 请求下载的次数 用于在下载失败时判断是否自动重新请求下载
/// 如果是分店是否自动到总店服务器下载文件
///
public string ReceiveFileCommandToServer(MemoryStream memoryMS = null, HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, string saveFileFullName = "", string serverFileFullName = "", BackgroundWorker backgroundWorker = null)
{
string tempMsg = "";
// if (!isFileServerIng)
{
try
{
bool ret = false;
TCP_NetworkClient myDownLoadClient = this.TFileClient;
if (myDownLoadClient.AppState != HPSocketCS.Extended.AppState.Started)
{
myDownLoadClient.ConnectionServer();
}
if (myDownLoadClient.AppState == HPSocketCS.Extended.AppState.Started)
{
if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
{
//如果是下载头像时设置头像在服务器上的路径
serverFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(serverFileFullName);
}
ServerFileInfo downloadFileInfo = myDownLoadClient.GetServerFileInfo(serverFileFullName);
if (downloadFileInfo.IsExists)
{
if (memoryMS == null && saveFileFullName.Trim().Length > 0)
{
if (downloadFileInfo.FileSize < HPSocketCS.Sdk.FileMD5VerifySize && downloadFileInfo.FileMd5.Trim().Length > 0 && System.IO.File.Exists(saveFileFullName.Trim()))
{
string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(saveFileFullName.Trim());
if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
{
ret = true;
}
else
{
ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
}
}
else
{
ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
}
}
else if (memoryMS != null)
{
string TempCachefilePath = TemporaryCachefilesPath + downloadFileInfo.FileMd5 + "_" + System.IO.Path.GetFileName(serverFileFullName);
byte[] TempCachefileBytes = null;
bool TempCachefileExists = false;
try
{
if (System.IO.File.Exists(TempCachefilePath))
{
TempCachefileBytes= System.IO.File.ReadAllBytes(TempCachefilePath);
TempCachefileExists = true;
}
}
catch { }
if (!TempCachefileExists)
{
MemoryStream recMemoryMS = myDownLoadClient.Client.DownloadMemoryStream(serverFileFullName, backgroundWorker);
if (recMemoryMS != null)
{
try
{
if (!System.IO.Directory.Exists(TemporaryCachefilesPath))
{
System.IO.Directory.CreateDirectory(TemporaryCachefilesPath);
}
recMemoryMS.Position = 0;
byte[] bytes = new byte[recMemoryMS.Length];
recMemoryMS.Read(bytes, 0, bytes.Length);
System.IO.File.WriteAllBytes(TempCachefilePath, bytes);
Array.Clear(bytes, 0, bytes.Length);
bytes = null;
}
catch { }
recMemoryMS.WriteTo(memoryMS);
memoryMS.Position = 0;
recMemoryMS.Close();
recMemoryMS.Dispose();
recMemoryMS = null;
ret = true;
}
}
else {
memoryMS.Write(TempCachefileBytes, 0, TempCachefileBytes.Length);
System.Array.Clear(TempCachefileBytes, 0, TempCachefileBytes.Length);
TempCachefileBytes = null;
ret = true;
}
}
else
{
return "下载请求错误";
}
}
else
{
return downloadFileInfo.GetMsg;
}
}
else
{
return "网络连接失败,请检查网络环境";
}
if (ret)
{
tempMsg = "下载成功";
}
else
{
tempMsg = "下载失败";
}
}
catch (Exception ex)
{
tempMsg = "下载出错:" + ex.Message;
}
// finally
// {
// isFileServerIng = false;
// }
}
return tempMsg;
}
#endregion
}
}