NetworkStream and TcpClient : read only necessary datas

Posted on 2006-04-05
Last Modified: 2008-02-01
Hi Experts,

I need to read my networkstream, so I do like this:
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);

The problem is that the buffer size (8192) > my datas(20).
So, finally I read the networkstream and I get a string length=8192 instead of a string length=20.

How can I get the only datas I need ?

Thanks in advance for your help.
Question by:noulouk
    1 Comment
    LVL 11

    Accepted Solution

    The System.Net.Sockets.NetworkStream.Read method returns an integer reporting the number of bytes that were actually received:

      byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

      int received = networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
      byte[] data = new byte[received];
      System.Array.Copy(bytes, data, received);

    In this example, if 20 bytes of data were actually received, the 'data' array would have only have 20 elements.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    In one of my recent projects, I was working with IP cameras, I need to take some pictures from the camera and do some processing on it. The first step, was to retrieve the image from camera into Image object. So that it can be displayed or …
    Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now