FileStream question

Can someone tell me if the explanation of this code bellow is correct? I'm having a problem on what the while statement mean...

 using (FileStream fs = fi.Open(FileMode.Open, FileAccess.Read))
           //Create a byte array b of size 1024
            byte[] b = new byte[1024];
           //Declare an instance of the UTF8Encoding
            UTF8Encoding temp = new UTF8Encoding(true);

            // Not sure what this code does bellow?
            while (fs.Read(b,0,b.Length) > 0)

                //Try to write to the file.
            catch (Exception e)
                Console.WriteLine("Writing was disallowed, as expected: {0}",
Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
Small correction to Shaun_Kline's statement above:

The while statement will read data from the file stream in *at most* 1024 bytes...
The last iteration of the while could read less than 1024 bytes.

And actually you should be capturing the number of bytes read by the Read method and using that value as the length to the Write method. Since you are reusing the same buffer, there will be junk at the end of the buffer from the last read which will not get overwritten by the next Read. You only want to write out as much as you read, not the full length of the buffer.
Shaun KlineLead Software EngineerCommented:
The while statement will read data from the file stream in 1024 bytes and write those bytes out to the console using UTF-8 encoding.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.