Who told you that you need to loop anything? It's totally up to you and depends on the operation you need to do. Remember that if the file is small enough to fit in memory, you don't need to directly use file stream at all, because you could use
System.IO.File
methods
ReadAllBytes
,
ReadAllLines
or
ReadAllText
:
http://msdn.microsoft.com/en-us/library/system.io.file.aspx[
^].
Therefore, the direct use of file streams is only required when you need to read just some small part of the file, using one or another algorithm, and not always a dumb loop.
Before getting to file streams, I would like to note that, in most cases, you should better use the classes
System.IO.StreamReader
,
System.IO.StreamWriter
,
System.IO.BinaryReader
or
System.IO.BinaryWriter
:
http://msdn.microsoft.com/en-us/library/vstudio/system.io.streamreader[
^],
http://msdn.microsoft.com/en-us/library/vstudio/system.io.streamwriter[
^],
http://msdn.microsoft.com/en-us/library/system.io.binaryreader%28v=vs.110%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx[
^].
Usually you need to use file streams directly in more complex cases, when you need very irregular read/write or read and write operations on the same stream.
Now, we're coming to the need of the return of the
System.IO.FileStream.Read
operation. It returns then number of
actually read bytes. Why do you need it? Because you can hit the end of file. In this case, you don't need to calculate how many bytes to read. You read some chunk and return the actually read number of bytes. This is a legitimate operation; it won't throw an exception. Moreover, not only you don't want to bother about number of the bytes to the end of the file; sometimes you cannot know how many bytes you can read in principles. In some relatively rare cases, you don't have exclusive access to some streams. Say, you read it, and some other thread or even process modifies the stream. Remember, raw
FileStream
is designed for more tricky operations…
—SA