public void ReceiveFilesFromAsync(IPEndPointHolder ipEndPoint, TcpClient client, SendFiles sendFiles, bool receive, object state, UserReceiveFilesProgress progress, UserReceiveFilesComplete complete) { new Thread(new ThreadStart(() => { try { ReceiveFilesFrom(ipEndPoint, client, sendFiles, receive, state, progress); if (complete != null) { complete(sendFiles, ipEndPoint, state, null); } } catch (Exception e) { if (complete != null) { complete(sendFiles, ipEndPoint, state, e); } } })).Start(); }
public void ReceiveFilesFrom(IPEndPointHolder ipEndPoint, TcpClient client, SendFiles sendFiles, bool receive, object state, UserReceiveFilesProgress progress) { try { byte[] bytes = new byte[1024]; NetworkStream networkStream = client.GetStream(); { byte[] buffer = Encoding.UTF8.GetBytes(Helper.XmlSerialize <SendFilesData>(new SendFilesData() { UserAddress = new UserAddress() { Address = Helper.LocalIPAddress(), Port = AirClient.DefaultPort }, Status = receive ? "allowed" : "denied" })); networkStream.Write(buffer, 0, buffer.Length); } if (!receive) { throw new OperationCanceledException(); } int i = 0; long n = 0; bool cancel = false; long totalSize = 0, receivedTotal = 0, receivedCurrent = 0; foreach (SendFile file in sendFiles.Files) { totalSize += file.Size; } string folder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Air File Exchange\\"; Directory.CreateDirectory(folder); foreach (SendFile file in sendFiles.Files) { using (FileStream fileStream = new FileStream(folder + file.Name, FileMode.OpenOrCreate, FileAccess.Write)) { fileStream.SetLength(0); receivedCurrent = 0; if (i - n > 0) { fileStream.Write(bytes, (int)n, i - (int)n); receivedCurrent += i - (int)n; receivedTotal += i - (int)n; if (progress != null) { progress(file, ipEndPoint, receivedCurrent, file.Size, receivedTotal, totalSize, state, out cancel); } } while (!cancel && (i = networkStream.Read(bytes, 0, bytes.Length)) != 0) { n = file.Size - fileStream.Length; if (i <= n) { n = i; } fileStream.Write(bytes, 0, (int)n); receivedCurrent += n; receivedTotal += n; if (progress != null) { progress(file, ipEndPoint, receivedCurrent, file.Size, receivedTotal, totalSize, state, out cancel); } if (file.Size == fileStream.Length) { break; } } } if (cancel) { throw new OperationCanceledException(); } } if (totalSize > receivedTotal) { throw new OperationCanceledException(); } } finally { client.Close(); } }