Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Got the code below from MSDN.

So, I don't understand why I had to loop FileStream.Read when it return the same value as the file length everytime.
The numBytesToRead will end up zero and FileStream.Read only executed once.
The comment said that "read may return anything from 0 to numBytesToRead", that means from offset to count right?
So can someone explain why and what's the function of offset and count?
Thanks before.

C#
public static void Main()
{
    // Specify a file to read from and to create. 
    string pathSource = @"c:\tests\source.txt";
    string pathNew = @"c:\tests\newfile.txt";

    try
    {

        using (FileStream fsSource = new FileStream(pathSource,
            FileMode.Open, FileAccess.Read))
        {

            // Read the source file into a byte array. 
            byte[] bytes = new byte[fsSource.Length];
            int numBytesToRead = (int)fsSource.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to numBytesToRead. 
                int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached. 
                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
             numBytesToRead = bytes.Length;

            // Write the byte array to the other FileStream. 
            using (FileStream fsNew = new FileStream(pathNew,
                FileMode.Create, FileAccess.Write))
            {
                fsNew.Write(bytes, 0, numBytesToRead);
            }
        }
    }
    catch (FileNotFoundException ioEx)
    {
        Console.WriteLine(ioEx.Message);
    }
}
Posted

Hi
You can visit the below link for details
http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx[^]
 
Share this answer
 
Comments
Midnight Ahri 15-Apr-14 0:46am    
Thank you, that's exactly where I got the code.
I had read offset and count explanation.
I need to know what condition that will cause the 'while' to loop more than once.
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
 
Share this answer
 
Comments
Midnight Ahri 15-Apr-14 1:20am    
Thank you very much for the explanation.
I read the file to do XOR with a key and rewrite it again.
ReadAllBytes corrupt the file when WriteAllBytes executed, so I think I will try FileStream first.
Sergey Alexandrovich Kryukov 15-Apr-14 1:36am    
You are welcome.
ReadAllBytes cannot corrupt anything; this is read-only operation on the file. Your observations might be incorrect.
If you read and write in sequence, nothing bad can happen. By the way, makes sure you close the files when you read or especially write operations are complete.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900