What does Filestream.Read return mean? How to read data in pieces and process them?

I am new to C #, so please bear with me. I read (using FileStream) data (fixed size) into a small array, process the data, and then read it again and so on to the end of the file.

I was thinking about using something like this:

            byte[] data = new byte[30];
            int numBytesToRead = (int)fStream.Length;
            int offset = 0;

            //reading
            while (numBytesToRead > 0)
            {
                fStream.Read(data, offset, 30);
                offset += 30;
                numBytesToRead -= 30;

                //do something with the data
            }

But I checked the documentation and their examples, and they stated that the return value of the above reading method:

"Type: System.Int32 The total number of bytes read in the buffer. This may be less than the number of bytes requested if the number of bytes is currently unavailable or zero if the end of the stream is reached."

, , ? , , . , , ?

.

+3
4

, . , , , ( ), .

, , , , , , . AFAIK , .

Read , , . offset, , , . , , offset.

, Read , , . , , .

byte[] data = new byte[30];
int numBytesToRead = (int)fStream.Length;
int offset = 0;

//reading
while (numBytesToRead > 0) {
  int len = fStream.Read(data, 0, data.Length);
  offset += len;
  numBytesToRead -= len;
  if (len == 0 && numBytesToRead > 0) {
    // error: unexpected end of file
  }
  //do something with the data (len bytes)
}
+4

, . :

  • ,
  • , .

, Stream , , .

:

byte[] buffer = new byte[BUFFER_SIZE];
int inBuffer;
while ((inBuffer = stream.Read(buffer, 0, buffer.Length)) > 0)
{
    // here you have "inBytes" number of bytes in the buffer
}
+3

FileStream Stream, Stream - , Read - . , , , . FileStream , :

  • value == ( Read):
  • < count && return value > 0: , .
  • return value == 0: . .
+1

FileStream, , HttpWebRequest.

FileStream.Read can theoretically return 1 byte. You should still process this small package.

But it will never return 0 unless there is a problem related to disconnecting the SMB connection, deleting the file, antivirus or getting to the end of the file.

There are better ways to read files. If you are dealing with a text file, use System.IO.StreamReader instead, as it handles various text encoding, line breaks, etc.

Also keep in mind that the maximum buffer size is 2 GB, so don't new buffer[fileStream.Length]

+1
source

Source: https://habr.com/ru/post/1793807/


All Articles