Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

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

.NET Framework 1.1

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.

[Visual Basic]
Public Sub New( _
   ByVal path As String, _
   ByVal mode As FileMode, _
   ByVal access As FileAccess, _
   ByVal share As FileShare, _
   ByVal bufferSize As Integer, _
   ByVal useAsync As Boolean _
)
[C#]
public FileStream(
   string path,
 FileMode mode,
 FileAccess access,
 FileShare share,
 int bufferSize,
 bool useAsync
);
[C++]
public: FileStream(
   String* path,
 FileMode mode,
 FileAccess access,
 FileShare share,
 int bufferSize,
 bool useAsync
);
[JScript]
public function FileStream(
   path : String,
 mode : FileMode,
 access : FileAccess,
 share : FileShare,
 bufferSize : int,
 useAsync : Boolean
);

Parameters

path
A relative or absolute path for the file that the current FileStream object will encapsulate.
mode
A FileMode constant that determines how to open or create the file.
access
A FileAccess constant that determines how the file can be accessed by the FileStream object. This gets the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.
share
A FileShare constant that determines how the file will be shared by processes.
bufferSize
The desired buffer size in bytes. For bufferSize values between zero and eight, the actual buffer size is set to eight bytes.
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 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.

Exceptions

Exception Type Condition
ArgumentNullException path is a null reference (Nothing in Visual Basic).
ArgumentException path is an empty string (""), contains only white space, or contains one or more invalid characters.
ArgumentOutOfRangeException bufferSize is negative or zero.

-or-

mode, access, or share contain an invalid value.

FileNotFoundException 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.
IOException An I/O error occurs, such as specifying FileMode.CreateNew and the file specified by path already exists.
SecurityException The caller does not have the required permission.
DirectoryNotFoundException The specified path is invalid, such as being on an unmapped drive.
UnauthorizedAccessException 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.
PathTooLongException 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.

Remarks

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.

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.

The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file. File.Move

FileInfo.MoveTo

Delete a file. File.Delete

FileInfo.Delete

Copy a file. File.Copy

FileInfo.CopyTo

Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File
Retrieve a file extension. Path.GetExtension
Retrieve the fully qualified path of a file. Path.GetFullPath
Retrieve the file name and extension from a path. Path.GetFileName
Change the extension of a file. Path.ChangeExtension

Example

[Visual Basic, C#, C++] 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.

[Visual Basic] 
Imports System
Imports System.IO
Imports System.Threading

Class FStream

    Shared Sub Main()

        ' Create a synchronization object that gets 
        ' signaled when verification is complete.
        Dim manualEvent As New ManualResetEvent(False)

        ' Create random data to write to the file.
        Dim writeArray(100000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(writeArray)

        Dim fStream As New FileStream("Test#@@#.dat", _
            FileMode.Create, FileAccess.ReadWrite, _
            FileShare.None, 4096, True)

        ' Check that the FileStream was opened asynchronously.
        If fStream.IsAsync = True
            Console.WriteLine("fStream was opened asynchronously.")
        Else
            Console.WriteLine("fStream was not opened asynchronously.")
        End If

        ' Asynchronously write to the file.
        Dim asyncResult As IAsyncResult = fStream.BeginWrite( _
            writeArray, 0, writeArray.Length, _
            AddressOf 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)
    End Sub

    ' 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.
    Private Shared Sub EndWriteCallback(asyncResult As IAsyncResult)
        Dim tempState As State = _
            DirectCast(asyncResult.AsyncState, State)
        Dim fStream As FileStream = tempState.FStream
        fStream.EndWrite(asyncResult)

        ' Asynchronously read back the written data.
        fStream.Position = 0
        asyncResult = fStream.BeginRead( _ 
            tempState.ReadArray, 0 , tempState.ReadArray.Length, _
            AddressOf EndReadCallback, tempState)

        ' Concurrently do other work, such as 
        ' logging the write operation.
    End Sub

    ' 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.
   Private Shared Sub EndReadCallback(asyncResult As IAsyncResult)
        Dim tempState As State = _
            DirectCast(asyncResult.AsyncState, State)
        Dim readCount As Integer = _
            tempState.FStream.EndRead(asyncResult)

        Dim i As Integer = 0
        While(i < readCount)
            If(tempState.ReadArray(i) <> tempState.WriteArray(i))
                Console.WriteLine("Error writing data.")
                tempState.FStream.Close()
                Return
            End If
            i += 1
        End While

        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()
    End Sub

    ' Maintain state information to be passed to 
    ' EndWriteCallback and EndReadCallback.
    Private Class State

        ' fStreamValue is used to read and write to the file.
        Dim fStreamValue As FileStream

        ' writeArrayValue stores data that is written to the file.
        Dim writeArrayValue As Byte()

        ' readArrayValue stores data that is read from the file.
        Dim readArrayValue As Byte()

        ' manualEvent signals the main thread 
        ' when verification is complete.
        Dim manualEventValue As ManualResetEvent 

        Sub New(aStream As FileStream, anArray As Byte(), _
            manualEvent As ManualResetEvent)

            fStreamValue     = aStream
            writeArrayValue  = anArray
            manualEventValue = manualEvent
            readArrayValue   = New Byte(anArray.Length - 1){}
        End Sub    

            Public ReadOnly Property FStream() As FileStream
                Get
                    Return fStreamValue
                End Get
            End Property

            Public ReadOnly Property WriteArray() As Byte()
                Get
                    Return writeArrayValue
                End Get
            End Property

            Public ReadOnly Property ReadArray() As Byte()
                Get
                    Return readArrayValue
                End Get
            End Property

            Public ReadOnly Property ManualEvent() As ManualResetEvent
                Get
                    Return manualEventValue
                End Get
            End Property
    End Class 
   
End Class

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

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Threading;

// Maintain state information to be passed to 
// EndWriteCallback and EndReadCallback.
__gc 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 __gc[];

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

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

public:
    State(FileStream* fStream, Byte writeArray __gc[], 
        ManualResetEvent* manualEvent)
    {
        this->fStream    = fStream;
        this->writeArray = writeArray;
        this->manualEvent = manualEvent;
        readArray = new Byte __gc[writeArray->Length];
    }

    __property FileStream* get_FStream()
    { return fStream; }

    __property Byte get_WriteArray() __gc[]
    { return writeArray; }

    __property Byte get_ReadArray() __gc[]
    { return readArray; }

    __property ManualResetEvent* get_ManualEvent()
    { return manualEvent; }
};

__gc class FStream
{
    // 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 = 
            dynamic_cast<State*>(asyncResult->AsyncState);
        int readCount = tempState->FStream->EndRead(asyncResult);

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

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

public:

    // 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 = 
            dynamic_cast<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(
            0, &FStream::EndReadCallback), tempState);

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

void main()
{
    // Create a synchronization object that gets 
    // signaled when verification is complete.
    ManualResetEvent* manualEvent = new ManualResetEvent(false);

    // Create the data to write to the file.
    Byte writeArray __gc[] = new Byte __gc [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(S"fStream was {0}opened asynchronously.",
        fStream->IsAsync ? S"" : S"not ");

    // Asynchronously write to the file.
    IAsyncResult* asyncResult = fStream->BeginWrite(
        writeArray, 0, writeArray->Length, 
        new AsyncCallback(0, &FStream::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);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

.NET Framework Security: 

See Also

FileStream Class | FileStream Members | System.IO Namespace | FileStream Constructor Overload List | File | Working with I/O | Reading Text from a File | Writing Text to a File

Show:
© 2015 Microsoft