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

FileStream Constructor (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.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

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


Type: System.String

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

Type: System.IO.FileMode

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

Type: System.IO.FileAccess

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.

Type: System.IO.FileShare

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

Type: System.Int32

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

Type: System.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 and BeginWrite 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.

Exception Condition

path is null.


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


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.


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.


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


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.

The .NET Framework 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.


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.


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.

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.

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;

        // 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.");
        Console.WriteLine("The data was written to {0} and verified.",

        // Signal the main thread that the verification is finished.

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


for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top
© 2015 Microsoft