6 out of 7 rated this helpful - Rate this topic

FileStream.Read Method

Reads a block of bytes from the stream and writes the data in a given buffer.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
public override int Read(
	byte[] array,
	int offset,
	int count
)

Parameters

array
Type: System.Byte[]
When this method returns, contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.
offset
Type: System.Int32
The byte offset in array at which the read bytes will be placed.
count
Type: System.Int32
The maximum number of bytes to read.

Return Value

Type: System.Int32
The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.
Exception Condition
ArgumentNullException

array is null.

ArgumentOutOfRangeException

offset or count is negative.

NotSupportedException

The stream does not support reading.

IOException

An I/O error occurred.

ArgumentException

offset and count describe an invalid range in array.

ObjectDisposedException

Methods were called after the stream was closed.

This method overrides Read.

The offset parameter gives the offset of the byte in array (the buffer index) at which to begin reading, and the count parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged.

The Read method returns zero only after reaching the end of the stream. Otherwise, Read always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to Read, the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

Use BinaryReader for reading primitive data types.

Interrupting a thread that is performing a read operation is not supported. Although the operations may appear to be successful after the thread is unblocked, these actions can decrease your application's performance and reliability.

For a list of common I/O tasks, see Common I/O Tasks.

The following example reads the contents from a FileStream and writes it into another FileStream.


using System;
using System.IO;

class Test
{

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);
    }
}
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Shortcut / less code (for files < 2GB)
DISCLAIMER: I recognize that casting the long to an int presents a problem for files > 2GB. However, I personally would never try to read a file > 4GB into a byte array in memory. I would switch more to a stream processing approach.

However, a shortcut to the code presented above might be to use a for-loop construct instead of the while presented above:

using System;
using System.IO;
class Test
{
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 fs = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fs.Length];
int len = (int)fs.Length;
for (int bRead=fs.Read(bytes,0,len); bRead>0;
Read=fs.Read(bytes,bRead,len-bRead));
// Write the byte array to the other FileStream.
using (FileStream fsNew = new FileStream(pathNew,
FileMode.Create, FileAccess.Write))
{
fsNew.Write(bytes, 0, bytes.Length);
}
}
}
catch (FileNotFoundException ioEx
{
Console.WriteLine(ioEx.Message);
}
}
}

"Subtle Bug" and Faulty Logic
While I agree that the cast to int is unnecessary, this will handle files up to 2 GB. It should also speed up the 'while(numBytesToRead > 0)' comparison. I am far more concerned about the break condition. First of all, you're making the 'if(n == 0)' comparison every loop, wasting CPU cycles and only saving two add/subtract operations at the end before it's caught by the while condition. More serious than inefficiency, I believe that the stream can get blocked for a loop and return nothing prematurely, exiting before the stream can be fully read. "Read may return anything from 0 to numBytesToRead."This could also go the other way, where the break condition is necessary to prevent an infinite loop.
Subtle bug.
The cast from long to integer on the line: int numBytesToRead = (int)fsSource.Length; will fail miserably if the length of fsSource is bigger than 2,147,483,647. So if you have a big file the while condition will evaluate to false and you won't read anything.