tags:

views:

16

answers:

1

Hi,

i am trying to read file from a stream.

and i am using stream.read method to read the bytes. So the code goes like below

FileByteStream.Read(buffer, 0, outputMessage.FileByteStream.Length)

Now the above gives me error because the last parameter "outputMessage.FileByteStream.Length" returns a long type value but the method expects an integer type.

Please advise.

+3  A: 

Convert it to an int...

FileByteStream.Read(buffer, 0, Convert.ToInt32(outputMessage.FileByteStream.Length))

It's probably an int because this operation blocks until it's done reading...so if you're in a high volume application, you may not want to block while you read in a massively large file.

If what you're reading in isn't reasonably sized, you may want to consider looping to read the data into a buffer (example from MSDN docs):

//s is the stream that I'm working with...
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int) s.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
    // Read may return anything from 0 to 10.
    int n = s.Read(bytes, numBytesRead, 10);
    // The end of the file is reached.
    if (n == 0)
    {
        break;
    }
    numBytesRead += n;
    numBytesToRead -= n;
}

This way you don't cast, and if you pick a reasonably large number to read into the buffer, you'll only go through the while loop once.

David Hoerster
+1 I was just writting same post ...
Ladislav Mrnka
thanks you all are champions
Amit