Export (0) Print
Expand All
8 out of 13 rated this helpful - Rate this topic

FileStream Class

Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
'Declaration
<ComVisibleAttribute(True)> _
Public Class FileStream _
	Inherits Stream

The FileStream type exposes the following members.

  NameDescription
Public methodFileStream(IntPtr, FileAccess) Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public methodFileStream(SafeFileHandle, FileAccess)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode)Initializes a new instance of the FileStream class with the specified path and creation mode.
Public methodFileStream(IntPtr, FileAccess, Boolean) Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.
Public methodFileStream(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.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess)Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.
Public methodFileStream(IntPtr, FileAccess, Boolean, Int32) 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.
Public methodFileStream(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.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess, FileShare)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.
Public methodFileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) 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.
Public methodSupported by the XNA FrameworkFileStream(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.
Public methodSupported by the XNA FrameworkFileStream(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.
Public methodFileStream(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.
Public methodFileStream(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.
Public methodFileStream(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.
Top
  NameDescription
Public propertySupported by the XNA FrameworkCanReadGets a value indicating whether the current stream supports reading. (Overrides Stream.CanRead.)
Public propertySupported by the XNA FrameworkCanSeekGets a value indicating whether the current stream supports seeking. (Overrides Stream.CanSeek.)
Public propertySupported by the XNA FrameworkCanTimeoutGets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public propertySupported by the XNA FrameworkCanWriteGets a value indicating whether the current stream supports writing. (Overrides Stream.CanWrite.)
Public propertyHandle Obsolete. Gets the operating system file handle for the file that the current FileStream object encapsulates.
Public propertySupported by the XNA FrameworkIsAsyncGets a value indicating whether the FileStream was opened asynchronously or synchronously.
Public propertySupported by the XNA FrameworkLengthGets the length in bytes of the stream. (Overrides Stream.Length.)
Public propertySupported by the XNA FrameworkNameGets the name of the FileStream that was passed to the constructor.
Public propertySupported by the XNA FrameworkPositionGets or sets the current position of this stream. (Overrides Stream.Position.)
Public propertySupported by the XNA FrameworkReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public propertySafeFileHandleGets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.
Public propertySupported by the XNA FrameworkWriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top
  NameDescription
Public methodSupported by the XNA FrameworkBeginReadBegins an asynchronous read operation. (Consider using ReadAsync instead; see the Remarks section.) (Overrides Stream.BeginRead(Byte(), Int32, Int32, AsyncCallback, Object).)

In XNA Framework 3.0, this member is inherited from Stream.BeginRead(Byte(), Int32, Int32, AsyncCallback, Object).
Public methodSupported by the XNA FrameworkBeginWriteBegins an asynchronous write operation. (Consider using WriteAsync instead; see the Remarks section.) (Overrides Stream.BeginWrite(Byte(), Int32, Int32, AsyncCallback, Object).)

In XNA Framework 3.0, this member is inherited from Stream.BeginWrite(Byte(), Int32, Int32, AsyncCallback, Object).
Public methodSupported by the XNA FrameworkCloseCloses the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. (Inherited from Stream.)
Public methodCopyTo(Stream)Reads the bytes from the current stream and writes them to another stream. (Inherited from Stream.)
Public methodCopyTo(Stream, Int32)Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Inherited from Stream.)
Public methodCopyToAsync(Stream)Asynchronously reads the bytes from the current stream and writes them to another stream. (Inherited from Stream.)
Public methodCopyToAsync(Stream, Int32)Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Inherited from Stream.)
Public methodCopyToAsync(Stream, Int32, CancellationToken)Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. (Inherited from Stream.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected methodSupported by the XNA FrameworkCreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public methodSupported by the XNA FrameworkDisposeReleases all resources used by the Stream. (Inherited from Stream.)
Protected methodSupported by the XNA FrameworkDispose(Boolean)Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).)
Public methodSupported by the XNA FrameworkEndReadWaits for the pending asynchronous read operation to complete. (Consider using ReadAsync instead; see the Remarks section.) (Overrides Stream.EndRead(IAsyncResult).)

In XNA Framework 3.0, this member is inherited from Stream.EndRead(IAsyncResult).
Public methodSupported by the XNA FrameworkEndWriteEnds an asynchronous write operation and blocks until the I/O operation is complete. (Consider using WriteAsync instead; see the Remarks section.) (Overrides Stream.EndWrite(IAsyncResult).)

In XNA Framework 3.0, this member is inherited from Stream.EndWrite(IAsyncResult).
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeEnsures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. (Overrides Object.Finalize.)
Public methodSupported by the XNA FrameworkFlushClears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush.)
Public methodFlush(Boolean)Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.
Public methodFlushAsyncAsynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Inherited from Stream.)
Public methodFlushAsync(CancellationToken)Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Overrides Stream.FlushAsync(CancellationToken).)
Public methodGetAccessControlGets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.
Public methodSupported by the XNA FrameworkGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodLockPrevents other processes from reading from or writing to the FileStream.
Protected methodSupported by the XNA FrameworkMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodObjectInvariantInfrastructure. Obsolete. Provides support for a Contract. (Inherited from Stream.)
Public methodSupported by the XNA FrameworkReadReads a block of bytes from the stream and writes the data in a given buffer. (Overrides Stream.Read(Byte(), Int32, Int32).)
Public methodReadAsync(Byte(), Int32, Int32)Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream.)
Public methodReadAsync(Byte(), Int32, Int32, CancellationToken)Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Overrides Stream.ReadAsync(Byte(), Int32, Int32, CancellationToken).)
Public methodSupported by the XNA FrameworkReadByteReads a byte from the file and advances the read position one byte. (Overrides Stream.ReadByte.)
Public methodSupported by the XNA FrameworkSeekSets the current position of this stream to the given value. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public methodSetAccessControlApplies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.
Public methodSupported by the XNA FrameworkSetLengthSets the length of this stream to the given value. (Overrides Stream.SetLength(Int64).)
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodUnlockAllows access by other processes to all or part of a file that was previously locked.
Public methodSupported by the XNA FrameworkWriteWrites a block of bytes to the file stream. (Overrides Stream.Write(Byte(), Int32, Int32).)
Public methodWriteAsync(Byte(), Int32, Int32)Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited from Stream.)
Public methodWriteAsync(Byte(), Int32, Int32, CancellationToken)Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Overrides Stream.WriteAsync(Byte(), Int32, Int32, CancellationToken).)
Public methodSupported by the XNA FrameworkWriteByteWrites a byte to the current position in the file stream. (Overrides Stream.WriteByte(Byte).)
Top
NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. FileStream buffers input and output for better performance.

Important noteImportant

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.

The IsAsync property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property 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.

The Seek method supports random access to files. Seek allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration.

NoteNote

Disk files always support random access. At the time of construction, the CanSeek property value is set to true or false depending on the underlying file type.If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property value is true. Otherwise, the CanSeek property value is false.

If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

For directory operations and other file operations, see the File, Directory, and Path classes. The File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and is similar to the FileStream class.

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

Detection of Stream Position Changes

When a FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the FileStream object.

If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

If an unexpected change in the handle position is detected in a call to the Write method, the contents of the buffer are discarded and an IOException exception is thrown.

A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

The following example demonstrates some of the FileStream constructors.

Imports System
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt" 

        ' Delete the file if it exists. 
        If File.Exists(path) Then
            File.Delete(path)
        End If 

        'Create the file. 
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:" & Environment.NewLine)

        Dim i As Integer 

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) As Byte 
        Dim temp As UTF8Encoding = New UTF8Encoding(True)

        Do While fs.Read(b, 0, b.Length) > 0
            Console.WriteLine(temp.GetString(b))
        Loop

        fs.Close()
    End Sub 

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub 
End Class

The following example shows how to write to a file asynchronously.

Imports System.IO
Imports System.Text

Class MainWindow
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim uniencoding As UnicodeEncoding = New UnicodeEncoding()
        Dim filename As String = "c:\Users\exampleuser\Documents\userinputlog.txt" 

        Dim result As Byte() = uniencoding.GetBytes(UserInput.Text)

        Using SourceStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)
            SourceStream.Seek(0, SeekOrigin.End)
            Await SourceStream.WriteAsync(result, 0, result.Length)
        End Using 
    End Sub 
End Class

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.