FileStream Class

Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

Syntax

Declaration

[ComVisible(true)]
public class FileStream : Stream, IDisposable

Inheritance Hierarchy

Constructors summary

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.

Initializes a new instance of the FileStream class with the specified path and creation mode.

Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

Properties summary

Gets a value indicating whether the current stream supports reading.

Gets a value indicating whether the current stream supports seeking.

Gets a value indicating whether the current stream supports writing.

Gets a value indicating whether the FileStream was opened asynchronously or synchronously.

Gets the length in bytes of the stream.

Gets the name of the FileStream that was passed to the constructor.

Gets or sets the current position of this stream.

Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.

Methods summary

Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.

Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.

Clears buffers for this stream and causes any buffered data to be written to the file.

Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

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

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

Reads a byte from the file and advances the read position one byte.

Sets the current position of this stream to the given value.

Sets the length of this stream to the given value.

Writes a block of bytes to the file stream.

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

Writes a byte to the current position in the file stream.

Constructors

  • FileStream(SafeFileHandle, FileAccess)

    Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

    public FileStream(SafeFileHandle handle, FileAccess access)

    Parameters

    • handle

      A file handle for the file that the current FileStream object will encapsulate.

    • access

      A constant that sets the CanRead and CanWrite properties of the FileStream object.

    Exceptions

    • access is not a field of FileAccess.

    • The caller does not have the required permission.

    • An I/O error, such as a disk error, occurred.

      -or-

      The stream has been closed.

    • The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

  • FileStream(SafeFileHandle, FileAccess, Int32)

    Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.

    public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)

    Parameters

    • handle

      A file handle for the file that the current FileStream object will encapsulate.

    • access

      A FileAccess constant that sets the CanRead and CanWrite properties of the FileStream object.

    • bufferSize

      A positive Int32 value greater than 0 indicating the buffer size. The default buffer size is 4096.

    Exceptions

    • The handle parameter is an invalid handle.

      -or-

      The handle parameter is a synchronous handle and it was used asynchronously.

    • The bufferSize parameter is negative.

    • An I/O error, such as a disk error, occurred.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

  • FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

    Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.

    [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)

    Parameters

    • handle

      A file handle for the file that this FileStream object will encapsulate.

    • access

      A constant that sets the CanRead and CanWrite properties of the FileStream object.

    • bufferSize

      A positive Int32 value greater than 0 indicating the buffer size. The default buffer size is 4096.

    • isAsync

      true if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false.

    Exceptions

    • The handle parameter is an invalid handle.

      -or-

      The handle parameter is a synchronous handle and it was used asynchronously.

    • The bufferSize parameter is negative.

    • An I/O error, such as a disk error, occurred.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

  • FileStream(String, FileMode)

    Initializes a new instance of the FileStream class with the specified path and creation mode.

    public FileStream(string path, FileMode mode)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    Exceptions

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • path is null.

    • The caller does not have the required permission.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The stream has been closed.

    • The specified path is invalid, such as being on an unmapped drive.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

    • mode contains an invalid value.

  • FileStream(String, FileMode, FileAccess)

    Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

    public FileStream(string path, FileMode mode, FileAccess access)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    • access

      A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

    Exceptions

    • path is null.

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The specified path is invalid, such as being on an unmapped drive.

    • The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

    • mode contains an invalid value.

  • FileStream(String, FileMode, FileAccess, FileShare)

    Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

    public FileStream(string path, FileMode mode, FileAccess access, FileShare share)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    • access

      A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

    • share

      A constant that determines how the file will be shared by processes.

    Exceptions

    • path is null.

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The specified path is invalid, such as being on an unmapped drive.

    • The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

    • mode contains an invalid value.

  • FileStream(String, FileMode, FileAccess, FileShare, Int32)

    Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.

    public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    • access

      A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

    • share

      A constant that determines how the file will be shared by processes.

    • bufferSize

      A positive Int32 value greater than 0 indicating the buffer size. The default buffer size is 4096.

    Exceptions

    • path is null.

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • bufferSize is negative or zero.

      -or-

      mode, access, or share contain an invalid value.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The specified path is invalid, such as being on an unmapped drive.

    • The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

  • FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)

    Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

    [SecurityCritical]
    public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    • access

      A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

    • share

      A constant that determines how the file will be shared by processes.

    • bufferSize

      A positive Int32 value greater than 0 indicating the buffer size. The default buffer size is 4096..

    • useAsync

      Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be opened synchronously depending on the platform. When opened asynchronously, the BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) and BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) methods perform better on large reads or writes, but they might be much slower for small reads or writes. If the application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.

    Exceptions

    • path is null.

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • bufferSize is negative or zero.

      -or-

      mode, access, or share contain an invalid value.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The specified path is invalid, such as being on an unmapped drive.

    • The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

  • FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)

    Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

    public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)

    Parameters

    • path

      A relative or absolute path for the file that the current FileStream object will encapsulate.

    • mode

      A constant that determines how to open or create the file.

    • access

      A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

    • share

      A constant that determines how the file will be shared by processes.

    • bufferSize

      A positive Int32 value greater than 0 indicating the buffer size. The default buffer size is 4096.

    • options

      A value that specifies additional file options.

    Exceptions

    • path is null.

    • path is an empty string (""), contains only white space, or contains one or more invalid characters.

      -or-

      path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

    • path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

    • bufferSize is negative or zero.

      -or-

      mode, access, or share contain an invalid value.

    • The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. The file must already exist in these modes.

    • An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

      -or-

      The stream has been closed.

    • The caller does not have the required permission.

    • The specified path is invalid, such as being on an unmapped drive.

    • The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

      -or-

      Encrypted is specified for options, but file encryption is not supported on the current platform.

    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

Properties

  • CanRead

    Gets a value indicating whether the current stream supports reading.

    public override bool CanRead { get; }

    Property Value

    • true if the stream supports reading; false if the stream is closed or was opened with write-only access.

    Overrides

  • CanSeek

    Gets a value indicating whether the current stream supports seeking.

    public override bool CanSeek { get; }

    Property Value

    • true if the stream supports seeking; false if the stream is closed or if the FileStream was constructed from an operating-system handle such as a pipe or output to the console.

    Overrides

  • CanWrite

    Gets a value indicating whether the current stream supports writing.

    public override bool CanWrite { get; }

    Property Value

    • true if the stream supports writing; false if the stream is closed or was opened with read-only access.

    Overrides

  • IsAsync

    Gets a value indicating whether the FileStream was opened asynchronously or synchronously.

    public virtual bool IsAsync { get; }

    Property Value

    • true if the FileStream was opened asynchronously; otherwise, false.

  • Length

    Gets the length in bytes of the stream.

    public override long Length { get; }

    Property Value

    • A long value representing the length of the stream in bytes.

    Exceptions

    Overrides

  • Name

    Gets the name of the FileStream that was passed to the constructor.

    public string Name { get; }

    Property Value

    • A string that is the name of the FileStream.

  • Position

    Gets or sets the current position of this stream.

    public override long Position { get; set; }

    Property Value

    • The current position of this stream.

    Exceptions

    Overrides

  • SafeFileHandle

    Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.

    public virtual SafeFileHandle SafeFileHandle
    {
        [SecurityCritical]
        get;
    }

    Property Value

    • An object that represents the operating system file handle for the file that the current FileStream object encapsulates.

Methods

  • Dispose(Boolean)

    Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.

    protected override void Dispose(bool disposing)

    Parameters

    • disposing

      true to release both managed and unmanaged resources; false to release only unmanaged resources.

    Overrides

  • Finalize()

    Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.

    protected void Finalize()
  • Flush()

    Clears buffers for this stream and causes any buffered data to be written to the file.

    public override void Flush()

    Exceptions

    Overrides

  • Flush(Boolean)

    Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

    public virtual void Flush(bool flushToDisk)

    Parameters

    • flushToDisk

      true to flush all intermediate file buffers; otherwise, false.

  • FlushAsync(CancellationToken)

    Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public override Task FlushAsync(CancellationToken cancellationToken)

    Parameters

    • cancellationToken

      The token to monitor for cancellation requests.

    Returns

    • A task that represents the asynchronous flush operation.

    Exceptions

    Overrides

  • Read(Byte[], Int32, Int32)

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

    public override int Read(byte[] array, int offset, int count)

    Parameters

    • array

      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

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

    • count

      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

    Overrides

  • ReadAsync(Byte[], Int32, Int32, CancellationToken)

    Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

    Parameters

    • buffer

      The buffer to write the data into.

    • offset

      The byte offset in buffer at which to begin writing data from the stream.

    • count

      The maximum number of bytes to read.

    • cancellationToken

      The token to monitor for cancellation requests.

    Returns

    • A task that represents the asynchronous read operation. The value of the TResult parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.

    Exceptions

    Overrides

  • ReadByte()

    Reads a byte from the file and advances the read position one byte.

    public override int ReadByte()

    Returns

    • The byte, cast to an Int32, or -1 if the end of the stream has been reached.

    Exceptions

    Overrides

  • Seek(Int64, SeekOrigin)

    Sets the current position of this stream to the given value.

    public override long Seek(long offset, SeekOrigin origin)

    Parameters

    • offset

      The point relative to origin from which to begin seeking.

    • origin

      Specifies the beginning, the end, or the current position as a reference point for offset, using a value of type SeekOrigin.

    Returns

    • The new position in the stream.

    Exceptions

    Overrides

  • SetLength(Int64)

    Sets the length of this stream to the given value.

    public override void SetLength(long value)

    Parameters

    • value

      The new length of the stream.

    Exceptions

    Overrides

  • Write(Byte[], Int32, Int32)

    Writes a block of bytes to the file stream.

    public override void Write(byte[] array, int offset, int count)

    Parameters

    • array

      The buffer containing data to write to the stream.

    • offset

      The zero-based byte offset in array from which to begin copying bytes to the stream.

    • count

      The maximum number of bytes to write.

    Exceptions

    Overrides

  • WriteAsync(Byte[], Int32, Int32, CancellationToken)

    Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

    Parameters

    • buffer

      The buffer to write data from.

    • offset

      The zero-based byte offset in buffer from which to begin copying bytes to the stream.

    • count

      The maximum number of bytes to write.

    • cancellationToken

      The token to monitor for cancellation requests.

    Returns

    • A task that represents the asynchronous write operation.

    Exceptions

    Overrides

  • WriteByte(Byte)

    Writes a byte to the current position in the file stream.

    public override void WriteByte(byte value)

    Parameters

    • value

      A byte to write to the stream.

    Exceptions

    Overrides

Details

Namespace

System.IO

Assembly

System.IO.FileSystem.dll