public FileControl(string fileName) { InitializeComponent(); this.txtFileName.Text = System.IO.Path.GetFileName(fileName); this._tcpFile = new TcpFile() { FileName = fileName }; this.DataContext = this._tcpFile; }
private bool ReceiveComplete(TcpFile file) { try { this._socket.Receive(this._buffer); this._socket.ReceiveTimeout = 30000; bool result = (FileCommand)this._buffer[0] == FileCommand.EndSendFileSuccess_Resp ? true : false; file.ProgressText = result ? "发送成功" : "发送失败"; return result; } catch { return false; } }
/// <summary> /// 发送文件 /// </summary> /// <param name="fileName"></param> public void SendFile(TcpFile file) { ThreadPool.QueueUserWorkItem((object o) => { try { FileInfo info = new FileInfo(file.FileName); long len = info.Length; file.FileName = System.IO.Path.GetFileName(info.Name); FileCapacityInfo fileCapacity = GetFileCapacityInfo(len); file.ProgressMaximum=len; file.ProgressText = string.Format("({0}{1})", fileCapacity.Value.ToString("F2"), fileCapacity.Type.ToString()); SendData(file.FileName); if (!Receive(FileCommand.BeginSendFile_Resp)) { return; } byte[] name = Encoding.UTF8.GetBytes(file.FileName); byte[] nameLength = BitConverter.GetBytes(name.Length); using (FileStream fs = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { long total = 0; int count = 0; double currentLength = 0; byte[] buffer = new byte[this._buffer.Length - 10 - name.Length]; do { count = fs.Read(buffer, 0, buffer.Length); SendData(file.FileName,buffer, count); if (!Receive(FileCommand.SendFile_Resp)) { Console.WriteLine("aaaabbb"); return; } total += count; currentLength = GetCurrentLength(total, fileCapacity.Type); file.ProgressText = string.Format("({0}/{1}{2})", fileCapacity.Value.ToString("F2"), currentLength.ToString("F2"), fileCapacity.Type.ToString()); file.ProgressValue = total; } while (total < len); } SendData(len); ReceiveComplete(file); } catch(Exception ex) { Console.WriteLine(ex.Message); } }); }