using System.Net.Sockets; TcpClient client = new TcpClient("localhost", 1234); NetworkStream stream = client.GetStream(); MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); byte[] data = memoryStream.ToArray(); client.Close();
using System.IO.Pipelines; using System.Net.Sockets; TcpClient client = new TcpClient("localhost", 1234); NetworkStream stream = client.GetStream(); PipeWriter writer = PipeWriter.Create(memoryStream); stream.CopyToAsync(writer); await writer.CompleteAsync(); client.Close();In this example, we are using the PipeWriter class from the System.IO.Pipelines namespace to write the data from the NetworkStream to the memory stream asynchronously. This method is useful when dealing with large amounts of data to avoid blocking the thread while the data is being copied. Package library used: System.Net.Sockets and System.IO.Pipelines.