C# bitmap images, byte arrays and streams!

后端 未结 5 707
醉梦人生
醉梦人生 2021-01-25 17:12

I have a function which extracts a file into a byte array (data).

        int contentLength = postedFile.ContentLength;
        byte[] data = new byte[contentLen         


        
5条回答
  •  天命终不由人
    2021-01-25 17:22

    That's most likely because you didn't get all the file data into the byte array. The Read method doesn't have to return as many bytes as you request, and it returns the number of bytes actually put in the array. You have to loop until you have gotten all the data:

    int contentLength = postedFile.ContentLength;
    byte[] data = new byte[contentLength];
    for (int pos = 0; pos < contentLength; ) {
       pos += postedFile.InputStream.Read(data, pos, contentLength - pos);
    }
    

    This is a common mistake when reading from a stream. I have seen this problem a lot of times.

    Edit:
    With the check for an early end of stream, as Matthew suggested, the code would be:

    int contentLength = postedFile.ContentLength;
    byte[] data = new byte[contentLength];
    for (int pos = 0; pos < contentLength; ) {
       int len = postedFile.InputStream.Read(data, pos, contentLength - pos);
       if (len == 0) {
          throw new ApplicationException("Upload aborted.");
       }
       pos += len;
    }
    

提交回复
热议问题