Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
FileStream Constructor (String, FileMode)

FileStream Constructor (String, FileMode)

.NET Framework 1.1

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

[Visual Basic]
Public Sub New( _
   ByVal path As String, _
   ByVal mode As FileMode _
public FileStream(
   string path,
 FileMode mode
public: FileStream(
   String* path,
 FileMode mode
public function FileStream(
   path : String,
 mode : FileMode


A relative or absolute path for the file that the current FileStream object will encapsulate.
A FileMode constant that determines how to open or create the file.


Exception Type Condition
ArgumentException path is an empty string (""), contains only white space, or contains one or more invalid characters.
ArgumentNullException path is a null reference (Nothing in Visual Basic).
SecurityException The caller does not have the required permission.
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.
DirectoryNotFoundException The specified path is invalid, such as being on an unmapped drive.
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.
ArgumentOutOfRangeException mode contains an invalid value.


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.

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.

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



Rename or move a file. File.Move


Delete a file. File.Delete


Copy a file. File.Copy


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


[Visual Basic, C#, C++] The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

[Visual Basic] 
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Text

Class FStream

    Shared Sub Main()

        Const fileName As String = "Test#@@#.dat"

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

        Dim fileStream As FileStream = _
            new FileStream(fileName, FileMode.Create)

            ' Write the data to the file, byte by byte.
            For i As Integer = 0 To dataArray.Length - 1
            Next i

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

            ' Read and verify the data.
            For i As Integer = 0 To _
                CType(fileStream.Length, Integer) - 1

                If dataArray(i) <> fileStream.ReadByte() Then
                    Console.WriteLine("Error writing data.")
                End If
            Next i
            Console.WriteLine("The data was written to {0} " & _
                "and verified.", fileStream.Name)
        End Try
    End Sub
End Class

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);

            fileStream = new FileStream(fileName, FileMode.Create))
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; 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.");
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);

#using <mscorlib.dll>
using namespace System;
using namespace System::IO;

void main()
    String* fileName = "Test@##@.dat";

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

    FileStream* fileStream = 
        new FileStream(fileName, FileMode::Create);
        // Write the data to the file, byte by byte.
        for(int i = 0; i < dataArray->Length; 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(S"Error writing data.");
        Console::WriteLine(S"The data was written to {0} " 
            S"and verified.", fileStream->Name);

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


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 | InvalidPathChars | Working with I/O | Reading Text from a File | Writing Text to a File

© 2015 Microsoft