tags:

views:

54

answers:

3
public static void ReadWholeArray (Stream stream, byte[] data)
{
    int offset=0;
    int remaining = data.Length;
    while (remaining > 0)
    {
        int read = stream.Read(data, offset, remaining);
        if (read <= 0)
            throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
        remaining -= read;
        offset += read;
     }
}

size of byte array data is 2682 on the first iteration of while loop the value of read is 1658 on the next iteration after executing the line

int read = stream.Read(data, offset, remaining);

the program is not responding

what is the problem?

A: 

You have not set a ReadTimeout at the stream and there is no data so the call blocks until data is available.

Check the properties of the Stream .ReadTimeout and .WriteTimeout.

Also, have in mind that you know the data you need but not how much data will come (fails, bugs, etc) so you should check that too.

SoMoS
A: 

Whatever is providing your stream is blocking until data is available. From MSDN's docs on Stream.Read:

The implementation will block until at least one byte of data can be read, in the event that no data is available. Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file)

You can set a read timeout on the stream to prevent blocking forever.

As an aside, note that reading from the stream will move the current position, so with your offset logic you may be skipping large chunks of the input stream.

Philip Rieck
A: 

You can try this. This code will read bytes from stream to the byte[]:

    public static byte[] GetBytesFromStream()
    {
        FileStream fs = new FileStream("d:/pic.jpg", FileMode.Create);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, (int)fs.Length);
        fs.Close();
        return bytes;
    }
Polaris
This still has the issue of FileStream.Read not returing all the data, so you would need a loop to make sure all the data is read.
SwDevMan81
there is a method for this already. File.ReadAllBytes()
Bryan