开发者

stream.read method accepts length as integer type ??? where as

开发者 https://www.devze.com 2023-01-14 07:26 出处:网络
i am trying to rea开发者_如何学JAVAd file from a stream. and i am using stream.read method to read the bytes. So the code goes like below

i am trying to rea开发者_如何学JAVAd 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消