Export (0) Print
Expand All

FileStream Constructor

.NET Framework 1.1

Initializes a new instance of the FileStream class.

Overload List

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

[Visual Basic] Public Sub New(IntPtr, FileAccess)
[C#] public FileStream(IntPtr, FileAccess);
[C++] public: FileStream(IntPtr, FileAccess);
[JScript] public function FileStream(IntPtr, FileAccess);

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

Supported by the .NET Compact Framework.

[Visual Basic] Public Sub New(String, FileMode)
[C#] public FileStream(string, FileMode);
[C++] public: FileStream(String*, FileMode);
[JScript] public function FileStream(String, FileMode);

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

[Visual Basic] Public Sub New(IntPtr, FileAccess, Boolean)
[C#] public FileStream(IntPtr, FileAccess, bool);
[C++] public: FileStream(IntPtr, FileAccess, bool);
[JScript] public function FileStream(IntPtr, FileAccess, Boolean);

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

Supported by the .NET Compact Framework.

[Visual Basic] Public Sub New(String, FileMode, FileAccess)
[C#] public FileStream(string, FileMode, FileAccess);
[C++] public: FileStream(String*, FileMode, FileAccess);
[JScript] public function FileStream(String, FileMode, FileAccess);

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.

[Visual Basic] Public Sub New(IntPtr, FileAccess, Boolean, Integer)
[C#] public FileStream(IntPtr, FileAccess, bool, int);
[C++] public: FileStream(IntPtr, FileAccess, bool, int);
[JScript] public function FileStream(IntPtr, FileAccess, Boolean, int);

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

Supported by the .NET Compact Framework.

[Visual Basic] Public Sub New(String, FileMode, FileAccess, FileShare)
[C#] public FileStream(string, FileMode, FileAccess, FileShare);
[C++] public: FileStream(String*, FileMode, FileAccess, FileShare);
[JScript] public function FileStream(String, FileMode, FileAccess, FileShare);

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.

[Visual Basic] Public Sub New(IntPtr, FileAccess, Boolean, Integer, Boolean)
[C#] public FileStream(IntPtr, FileAccess, bool, int, bool);
[C++] public: FileStream(IntPtr, FileAccess, bool, int, bool);
[JScript] public function FileStream(IntPtr, FileAccess, Boolean, int, Boolean);

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

Supported by the .NET Compact Framework.

[Visual Basic] Public Sub New(String, FileMode, FileAccess, FileShare, Integer)
[C#] public FileStream(string, FileMode, FileAccess, FileShare, int);
[C++] public: FileStream(String*, FileMode, FileAccess, FileShare, int);
[JScript] public function FileStream(String, FileMode, FileAccess, FileShare, int);

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.

Supported by the .NET Compact Framework.

[Visual Basic] Public Sub New(String, FileMode, FileAccess, FileShare, Integer, Boolean)
[C#] public FileStream(string, FileMode, FileAccess, FileShare, int, bool);
[C++] public: FileStream(String*, FileMode, FileAccess, FileShare, int, bool);
[JScript] public function FileStream(String, FileMode, FileAccess, FileShare, int, Boolean);

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, C#, C++] Note   This example shows how to use one of the overloaded versions of the FileStream constructor. For other examples that might be available, see the individual overload topics.
[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.

See Also

FileStream Class | FileStream Members | System.IO Namespace

Show:
© 2014 Microsoft