S
S
Senture2018-12-08 14:40:12
C++ / C#
Senture, 2018-12-08 14:40:12

How to fix System.IO.EndOfStreamException: "Cannot read past end of stream." in MemoryStream?

Greetings, I need your help, I don’t know what to do anymore, I searched the entire Internet, and Position = 0 helps everyone, but not for me.

private static byte[] buffer = new byte[1024];
    private static MemoryStream stream = new MemoryStream(buffer);
    private static BinaryWriter writer = new BinaryWriter(stream);
    private static BinaryReader reader = new BinaryReader(stream);

    private List<string> listCode = new List<string>();

void ReceiveData()
    {
        int bytes = 0;

        EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);
        listCode.Clear();

        do
        {
            bytes = socket.ReceiveFrom(buffer, ref remoteIp);
        }
        while (socket.Available > 0);


        bool getData = true;

        stream.Position = 0;

        try
        {
            while (getData)
            {
                string data = reader.ReadString(); // ВОТ ТУТ КОД ВЫДАЕТ ИСКЛЮЧЕНИЕ ПОСЛЕ ТОГО КАК ДАННЫЕ С СЕРВЕРА ПРИХОДЯТ 2-ОЙ РАЗ
                if (data != "")
                    listCode.Add(data);
                else
                    getData = false;
            }
        }
        catch(Exception ex)
        {
            Debug.Log(ex.Message);
        }

        stream.SetLength(0);
        stream.Position = 0;

        IPEndPoint remoteFullIP = remoteIp as IPEndPoint;
    }

Tell me please! Thanks to all!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2018-12-09
@Senture

while(reader.Position != reader.Length) // должно работать

For ReadString() , returning an empty string is perfectly reasonable behavior.
For example, if this comment were read, then your code would not reach this line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question