Bewerken

Share via


FileStream.Read Method

Definition

Overloads

Read(Byte[], Int32, Int32)

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

Read(Span<Byte>)

Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read.

Read(Byte[], Int32, Int32)

Source:
FileStream.cs
Source:
FileStream.cs
Source:
FileStream.cs

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

public:
 override int Read(cli::array <System::Byte> ^ array, int offset, int count);
public:
 override int Read(cli::array <System::Byte> ^ buffer, int offset, int count);
public override int Read (byte[] array, int offset, int count);
public override int Read (byte[] buffer, int offset, int count);
override this.Read : byte[] * int * int -> int
override this.Read : byte[] * int * int -> int
Public Overrides Function Read (array As Byte(), offset As Integer, count As Integer) As Integer
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

Parameters

arraybuffer
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
Int32

The byte offset in array at which the read bytes will be placed.

count
Int32

The maximum number of bytes to read.

Returns

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.

Exceptions

array is null.

offset or count is negative.

The stream does not support reading.

An I/O error occurred.

offset and count describe an invalid range in array.

Methods were called after the stream was closed.

Examples

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);
    }
}
}
open System.IO

// Specify a file to read from and to create.
let pathSource = @"c:\tests\source.txt"
let pathNew = @"c:\tests\newfile.txt"

try
    use fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read)

    // Read the source file into a byte array.
    let mutable numBytesToRead = int fsSource.Length
    let bytes = numBytesToRead |> Array.zeroCreate
    let mutable numBytesRead = 0

    while numBytesToRead > 0 do
        // Read may return anything from 0 to numBytesToRead.
        let n = fsSource.Read(bytes, numBytesRead, numBytesToRead)

        // Break when the end of the file is reached.
        if n <> 0 then
            numBytesRead <- numBytesRead + n
            numBytesToRead <- numBytesToRead - n

    let numBytesToRead = bytes.Length

    // Write the byte array to the other FileStream.
    use fsNew = new FileStream(pathNew, FileMode.Create, FileAccess.Write)
    fsNew.Write(bytes, 0, numBytesToRead)
with :? FileNotFoundException as ioEx ->
    printfn $"{ioEx.Message}"
Imports System.IO
Class Test
    
Public Shared Sub Main()
    ' Specify a file to read from and to create.
    Dim pathSource As String = "c:\tests\source.txt"
    Dim pathNew As String = "c:\tests\newfile.txt"
    Try 
        Using fsSource As FileStream = New FileStream(pathSource, _
            FileMode.Open, FileAccess.Read)
            ' Read the source file into a byte array.
                Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
                Dim numBytesToRead As Integer = CType(fsSource.Length,Integer)
                Dim numBytesRead As Integer = 0

                While (numBytesToRead > 0)
                    ' Read may return anything from 0 to numBytesToRead.
                    Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
                        numBytesToRead)
                    ' Break when the end of the file is reached.
                    If (n = 0) Then
                        Exit While
                    End If
                    numBytesRead = (numBytesRead + n)
                    numBytesToRead = (numBytesToRead - n)

                End While
            numBytesToRead = bytes.Length

            ' Write the byte array to the other FileStream.
            Using fsNew As FileStream = New FileStream(pathNew, _
                FileMode.Create, FileAccess.Write)
                fsNew.Write(bytes, 0, numBytesToRead)
            End Using
        End Using
    Catch ioEx As FileNotFoundException
        Console.WriteLine(ioEx.Message)
    End Try
End Sub
End Class

Remarks

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.

Do not interrupt a thread that is performing a read operation. Although the application may appear to run successfully after the thread is unblocked, the interruption can decrease your application's performance and reliability.

For a list of common file and directory operations, see Common I/O Tasks.

See also

Applies to

Read(Span<Byte>)

Source:
FileStream.cs
Source:
FileStream.cs
Source:
FileStream.cs

Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read.

public:
 override int Read(Span<System::Byte> buffer);
public override int Read (Span<byte> buffer);
override this.Read : Span<byte> -> int
Public Overrides Function Read (buffer As Span(Of Byte)) As Integer

Parameters

buffer
Span<Byte>

A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current file stream.

Returns

The total number of bytes read into the buffer. This can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

Remarks

Use the CanRead property to determine whether the current instance supports reading. Use the ReadAsync method to read asynchronously from the current stream.

This method reads a maximum of buffer.Length bytes from the current file stream and stores them in buffer. The current position within the file stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the file stream remains unchanged. The method will block until at least one byte of data can be read, in the event that no data is available. Read returns 0 only when there is no more data in the file stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the file stream has not been reached.

Use BinaryReader for reading primitive data types.

Applies to