Edit

Share via


FileStream Constructors

Definition

Initializes a new instance of the FileStream class.

Overloads

FileStream(SafeFileHandle, FileAccess)

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

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

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.

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.

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
Obsolete.
Obsolete.
Obsolete.

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

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.

FileStream(IntPtr, FileAccess, Boolean, Int32)
Obsolete.
Obsolete.
Obsolete.

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

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.

FileStream(String, FileMode, FileAccess)

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

FileStream(IntPtr, FileAccess, Boolean)
Obsolete.
Obsolete.
Obsolete.

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

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.

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.

FileStream(String, FileStreamOptions)

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

FileStream(String, FileMode)

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

FileStream(IntPtr, FileAccess)
Obsolete.
Obsolete.
Obsolete.

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

FileStream(SafeFileHandle, FileAccess)

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

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

C#
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access);

Parameters

handle
SafeFileHandle

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

access
FileAccess

A bitwise combination of the enumeration values 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.

Remarks

When Close is called, the handle is also closed and the file's handle count is decremented.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.

C#
public FileStream(string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

rights
FileSystemRights

A bitwise combination of the enumeration values that determines the access rights to use when creating access and audit rules for the file.

share
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

bufferSize
Int32

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

options
FileOptions

A bitwise combination of the enumeration values that specifies additional file options.

fileSecurity
FileSecurity

An object that determines the access control and audit security for the file.

Exceptions

path is null.

.NET Framework and .NET Core versions older than 2.1: 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, rights, 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 rights requested is not permitted by the operating system for the specified path, such as when rights 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.

The current operating system is not Windows NT or later.

Examples

The following example writes data to a file and then reads the data using the FileStream object.

C#
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileStreamExample
    {
        public static void Main()
        {
            try
            {
                // Create a file and write data to it.

                // Create an array of bytes.
                byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");

                // Specify an access control list (ACL)
                FileSecurity fs = new FileSecurity();

                fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName",
                                                            FileSystemRights.ReadData,
                                                            AccessControlType.Allow));

                // Create a file using the FileStream class.
                FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs);

                // Write the number of bytes to the file.
                fWrite.WriteByte((byte)messageByte.Length);

                // Write the bytes to the file.
                fWrite.Write(messageByte, 0, messageByte.Length);

                // Close the stream.
                fWrite.Close();

                // Open a file and read the number of bytes.

                FileStream fRead = new FileStream("test.txt", FileMode.Open);

                // The first byte is the string length.
                int length = (int)fRead.ReadByte();

                // Create a new byte array for the data.
                byte[] readBytes = new byte[length];

                // Read the data from the file.
                fRead.Read(readBytes, 0, readBytes.Length);

                // Close the stream.
                fRead.Close();

                // Display the data.
                Console.WriteLine(Encoding.ASCII.GetString(readBytes));

                Console.WriteLine("Done writing and reading data.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
    }
}

Remarks

.NET Framework does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0".

Use this FileStream constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.

The fileOptions parameter is used to provide access to more advanced operations that you can use when creating a FileStream object.

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

Important

This constructor does not exist in .NET Core. Instead, starting in .NET Core 3.1, you can use the following extension method of the FileSystemAclExtensions class inside the System.Security.AccessControl assembly: Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity).

See also

Applies to

.NET Framework 4.8.1 and other versions
Product Versions
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

C#
public FileStream(string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

rights
FileSystemRights

A bitwise combination of the enumeration values that determines the access rights to use when creating access and audit rules for the file.

share
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

bufferSize
Int32

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

options
FileOptions

A bitwise combination of the enumeration values that specifies additional file options.

Exceptions

path is null.

.NET Framework and .NET Core versions older than 2.1: 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, rights, or share contains 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.

The current operating system is not Windows NT or later.

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 rights requested is not permitted by the operating system for the specified path, such as when rights 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.

Remarks

.NET Framework does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0".

Use this FileStream constructor to apply access rights at the point of creation of a file. To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.

The fileOptions parameter is used to provide access to more advanced operations that you can use when creating a FileStream object.

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET Framework 4.8.1 and other versions
Product Versions
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

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

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

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.

C#
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

access
FileAccess

A bitwise combination of the enumeration values 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
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

bufferSize
Int32

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

options
FileOptions

A bitwise combination of the enumeration values that specifies additional file options.

Exceptions

path is null.

.NET Framework and .NET Core versions older than 2.1: 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.

Examples

The following example writes data to a file and then reads the data using the FileStream object.

C#
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileStreamExample
    {
        public static void Main()
        {
            try
            {
                // Create a file and write data to it.

                // Create an array of bytes.
                byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");

                // Create a file using the FileStream class.
                FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None);

                // Write the number of bytes to the file.
                fWrite.WriteByte((byte)messageByte.Length);

                // Write the bytes to the file.
                fWrite.Write(messageByte, 0, messageByte.Length);

                // Close the stream.
                fWrite.Close();

                // Open a file and read the number of bytes.

                FileStream fRead = new FileStream("test.txt", FileMode.Open);

                // The first byte is the string length.
                int length = (int)fRead.ReadByte();

                // Create a new byte array for the data.
                byte[] readBytes = new byte[length];

                // Read the data from the file.
                fRead.Read(readBytes, 0, readBytes.Length);

                // Close the stream.
                fRead.Close();

                // Display the data.
                Console.WriteLine(Encoding.ASCII.GetString(readBytes));

                Console.WriteLine("Done writing and reading data.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
    }
}

Remarks

.NET doesn't support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The fileOptions parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

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

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

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

C#
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

access
FileAccess

A bitwise combination of the enumeration values 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
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

bufferSize
Int32

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

Exceptions

path is null.

.NET Framework and .NET Core versions older than 2.1: 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.

The specified path, file name, or both exceed the system-defined maximum length.

Remarks

.NET does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)

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

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

Caution

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

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

C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
C#
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
C#
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);

Parameters

handle
IntPtr

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

access
FileAccess

A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean

true if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize
Int32

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

isAsync
Boolean

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

Attributes

Exceptions

access is less than FileAccess.Read or greater than FileAccess.ReadWrite or bufferSize is less than or equal to 0.

The handle is invalid.

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.

Remarks

The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the Close method will also close the handle. In particular, the file's handle count is decremented. The FileStream object is given the specified buffer size.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions (Obsolete)
.NET (Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9)
.NET Framework 1.1 (2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1)
.NET Standard (2.0, 2.1)

FileStream(String, FileMode, FileAccess, FileShare)

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

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

C#
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

access
FileAccess

A bitwise combination of the enumeration values 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
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

Exceptions

path is null.

.NET Framework and .NET Core versions older than 2.1: 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.

mode contains an invalid value.

Examples

This code example is part of a larger example provided for the Lock method.

C#
using(FileStream fileStream = new FileStream(
    "Test#@@#.dat", FileMode.OpenOrCreate,
    FileAccess.ReadWrite, FileShare.ReadWrite))

Remarks

.NET doesn't support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). The buffer size is set to the default size of 4096 bytes (4 KB).

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(IntPtr, FileAccess, Boolean, Int32)

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

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

Caution

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

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

C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
C#
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
C#
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);

Parameters

handle
IntPtr

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

access
FileAccess

A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean

true if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize
Int32

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

Attributes

Exceptions

bufferSize 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.

Remarks

The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the Close method will also close the handle. In particular, the file's handle count is decremented. The FileStream object is given the specified buffer size.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions (Obsolete)
.NET (Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9)
.NET Framework 1.1 (2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1)
.NET Standard (2.0, 2.1)

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

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

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.

C#
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

access
FileAccess

A bitwise combination of the enumeration values 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
FileShare

A bitwise combination of the enumeration values that determines how the file will be shared by processes.

bufferSize
Int32

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

useAsync
Boolean

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.

.NET Framework and .NET Core versions older than 2.1: 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.

The specified path, file name, or both exceed the system-defined maximum length.

Examples

The following code example shows how to asynchronously write data to a file and then verify that the data was written correctly. A State object is created to pass information from the main thread to the EndReadCallback and EndWriteCallback methods.

C#
using System;
using System.IO;
using System.Threading;

class FStream
{
    static void Main()
    {
        // Create a synchronization object that gets
        // signaled when verification is complete.
        ManualResetEvent manualEvent = new ManualResetEvent(false);

        // Create random data to write to the file.
        byte[] writeArray = new byte[100000];
        new Random().NextBytes(writeArray);

        FileStream fStream =
            new FileStream("Test#@@#.dat", FileMode.Create,
            FileAccess.ReadWrite, FileShare.None, 4096, true);

        // Check that the FileStream was opened asynchronously.
        Console.WriteLine("fStream was {0}opened asynchronously.",
            fStream.IsAsync ? "" : "not ");

        // Asynchronously write to the file.
        IAsyncResult asyncResult = fStream.BeginWrite(
            writeArray, 0, writeArray.Length,
            new AsyncCallback(EndWriteCallback),
            new State(fStream, writeArray, manualEvent));

        // Concurrently do other work and then wait
        // for the data to be written and verified.
        manualEvent.WaitOne(5000, false);
    }

    // When BeginWrite is finished writing data to the file, the
    // EndWriteCallback method is called to end the asynchronous
    // write operation and then read back and verify the data.
    static void EndWriteCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        FileStream fStream = tempState.FStream;
        fStream.EndWrite(asyncResult);

        // Asynchronously read back the written data.
        fStream.Position = 0;
        asyncResult = fStream.BeginRead(
            tempState.ReadArray, 0 , tempState.ReadArray.Length,
            new AsyncCallback(EndReadCallback), tempState);

        // Concurrently do other work, such as
        // logging the write operation.
    }

    // When BeginRead is finished reading data from the file, the
    // EndReadCallback method is called to end the asynchronous
    // read operation and then verify the data.
    static void EndReadCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        int readCount = tempState.FStream.EndRead(asyncResult);

        int i = 0;
        while(i < readCount)
        {
            if(tempState.ReadArray[i] != tempState.WriteArray[i++])
            {
                Console.WriteLine("Error writing data.");
                tempState.FStream.Close();
                return;
            }
        }
        Console.WriteLine("The data was written to {0} and verified.",
            tempState.FStream.Name);
        tempState.FStream.Close();

        // Signal the main thread that the verification is finished.
        tempState.ManualEvent.Set();
    }

    // Maintain state information to be passed to
    // EndWriteCallback and EndReadCallback.
    class State
    {
        // fStream is used to read and write to the file.
        FileStream fStream;

        // writeArray stores data that is written to the file.
        byte[] writeArray;

        // readArray stores data that is read from the file.
        byte[] readArray;

        // manualEvent signals the main thread
        // when verification is complete.
        ManualResetEvent manualEvent;

        public State(FileStream fStream, byte[] writeArray,
            ManualResetEvent manualEvent)
        {
            this.fStream   = fStream;
            this.writeArray = writeArray;
            this.manualEvent = manualEvent;
            readArray = new byte[writeArray.Length];
        }

        public FileStream FStream
        { get{ return fStream; } }

        public byte[] WriteArray
        { get{ return writeArray; } }

        public byte[] ReadArray
        { get{ return readArray; } }

        public ManualResetEvent ManualEvent
        { get{ return manualEvent; } }
    }
}

Remarks

.NET does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(String, FileMode, FileAccess)

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

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

C#
public FileStream(string path, System.IO.FileMode mode, System.IO.FileAccess access);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

access
FileAccess

A bitwise combination of the enumeration values 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.

.NET Framework and .NET Core versions older than 2.1: 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.

mode contains an invalid value.

Remarks

.NET does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). The buffer size is set to the default size of 4096 bytes (4 KB).

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(IntPtr, FileAccess, Boolean)

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

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

Caution

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

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

C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
C#
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
C#
public FileStream(IntPtr handle, System.IO.FileAccess access, bool ownsHandle);

Parameters

handle
IntPtr

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

access
FileAccess

A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean

true if the file handle will be owned by this FileStream instance; otherwise, false.

Attributes

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.

Remarks

The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this process owns the handle, a call to the Close method will also close the handle and the file's handle count is decremented. The FileStream object is given the default buffer size of 4096 bytes.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling methods other than Close after you are done using the handle.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions (Obsolete)
.NET (Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9)
.NET Framework 1.1 (2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1)
.NET Standard (2.0, 2.1)

FileStream(SafeFileHandle, FileAccess, Int32)

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

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

C#
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize);

Parameters

handle
SafeFileHandle

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

access
FileAccess

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

bufferSize
Int32

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.

Remarks

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

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

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.

C#
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync);

Parameters

handle
SafeFileHandle

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

access
FileAccess

A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream object.

bufferSize
Int32

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

isAsync
Boolean

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.

Remarks

You set the isAsync parameter to true to open the file handle asynchronously. When the parameter is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the parameter does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the isAsync parameter is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(String, FileStreamOptions)

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

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

C#
public FileStream(string path, System.IO.FileStreamOptions options);

Parameters

path
String

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

options
FileStreamOptions

An object that describes optional FileStream parameters to use.

Exceptions

path or options 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:, or LPT1:, 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.

-or-

The disk was full (when PreallocationSize was provided and path was pointing to a regular file).

-or-

The file was too large (when PreallocationSize was provided and path was pointing to a regular file).

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.

Remarks

Specifying a value for PreallocationSize provides a hint about the preallocation size, but not a strong guarantee. For full usage details, see the documentation for PreallocationSize.

Applies to

.NET 9 and other versions
Product Versions
.NET 6, 7, 8, 9

FileStream(String, FileMode)

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

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

C#
public FileStream(string path, System.IO.FileMode mode);

Parameters

path
String

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

mode
FileMode

One of the enumeration values that determines how to open or create the file.

Exceptions

.NET Framework and .NET Core versions older than 2.1: 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.

path specifies a file that is read-only.

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.

mode contains an invalid value.

Examples

The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

C#
using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}

Remarks

.NET doesn't support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed).

You cannot use this constructor to open read-only files; instead, you must use a constructor that accepts a FileAccess parameter with the value set to FileAccess.Read.

The buffer size is set to the default size of 4096 bytes (4 KB).

Note

path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.

CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. For additional information, see CanSeek.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

For constructors without a FileAccess parameter, if the mode parameter is set to Append, Write is the default access. Otherwise, the access is set to ReadWrite.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

FileStream(IntPtr, FileAccess)

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

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202

Caution

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.

Caution

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202

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

C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access);
C#
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")]
public FileStream(IntPtr handle, System.IO.FileAccess access);
C#
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, System.IO.FileAccess access);
C#
public FileStream(IntPtr handle, System.IO.FileAccess access);

Parameters

handle
IntPtr

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

access
FileAccess

A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream object.

Attributes

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.

Remarks

When Close is called, the handle is also closed and the file's handle count is decremented.

FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

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

See also

Applies to

.NET 9 and other versions
Product Versions (Obsolete)
.NET (Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9)
.NET Framework 1.1 (2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1)
.NET Standard (2.0, 2.1)