FileStream Class
Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
Assembly: mscorlib (in mscorlib.dll)
The FileStream type exposes the following members.
| Name | Description | |
|---|---|---|
![]() | FileStream(IntPtr, FileAccess) | Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
![]() | FileStream(SafeFileHandle, FileAccess) | Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
![]() ![]() | FileStream(String, FileMode) | Initializes a new instance of the FileStream class with the specified path and creation mode. |
![]() | FileStream(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. |
![]() | FileStream(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. |
![]() ![]() | FileStream(String, FileMode, FileAccess) | Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission. |
![]() | FileStream(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. |
![]() | FileStream(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. |
![]() ![]() | FileStream(String, FileMode, FileAccess, FileShare) | Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission. |
![]() | FileStream(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. |
![]() ![]() | FileStream(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. |
![]() ![]() | FileStream(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. |
![]() | FileStream(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. |
![]() | FileStream(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. |
![]() | FileStream(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. |
| Name | Description | |
|---|---|---|
![]() ![]() | CanRead | Gets a value indicating whether the current stream supports reading. (Overrides Stream.CanRead.) |
![]() ![]() | CanSeek | Gets a value indicating whether the current stream supports seeking. (Overrides Stream.CanSeek.) |
![]() ![]() | CanTimeout | Gets a value that determines whether the current stream can time out. (Inherited from Stream.) |
![]() ![]() | CanWrite | Gets a value indicating whether the current stream supports writing. (Overrides Stream.CanWrite.) |
![]() | Handle | Obsolete. Gets the operating system file handle for the file that the current FileStream object encapsulates. |
![]() ![]() | IsAsync | Gets a value indicating whether the FileStream was opened asynchronously or synchronously. |
![]() ![]() | Length | Gets the length in bytes of the stream. (Overrides Stream.Length.) |
![]() ![]() | Name | Gets the name of the FileStream that was passed to the constructor. |
![]() ![]() | Position | Gets or sets the current position of this stream. (Overrides Stream.Position.) |
![]() ![]() | ReadTimeout | Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.) |
![]() | SafeFileHandle | Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates. |
![]() ![]() | WriteTimeout | Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.) |
| Name | Description | |
|---|---|---|
![]() ![]() | BeginRead | Begins an asynchronous read. (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). |
![]() ![]() | BeginWrite | Begins an asynchronous write. (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). |
![]() ![]() | Close | Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.) |
![]() | CopyTo(Stream) | Reads the bytes from the current stream and writes them to the destination stream. (Inherited from Stream.) |
![]() | CopyTo(Stream, Int32) | Reads all the bytes from the current stream and writes them to a destination stream, using a specified buffer size. (Inherited from Stream.) |
![]() | CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) |
![]() ![]() | CreateWaitHandle | Obsolete. Allocates a WaitHandle object. (Inherited from Stream.) |
![]() ![]() | Dispose | Releases all resources used by the Stream. (Inherited from Stream.) |
![]() ![]() | Dispose(Boolean) | Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).) |
![]() ![]() | EndRead | Waits for the pending asynchronous read to complete. (Overrides Stream.EndRead(IAsyncResult).) In XNA Framework 3.0, this member is inherited from Stream.EndRead(IAsyncResult). |
![]() ![]() | EndWrite | Ends an asynchronous write, blocking until the I/O operation has completed. (Overrides Stream.EndWrite(IAsyncResult).) In XNA Framework 3.0, this member is inherited from Stream.EndWrite(IAsyncResult). |
![]() ![]() | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) |
![]() ![]() | Finalize | Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. (Overrides Object.Finalize.) |
![]() ![]() | Flush | Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush.) |
![]() | Flush(Boolean) | Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers. |
![]() | GetAccessControl | Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object. |
![]() ![]() | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) |
![]() | GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
![]() ![]() | GetType | Gets the Type of the current instance. (Inherited from Object.) |
![]() | InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
![]() | Lock | Prevents other processes from reading from or writing to the FileStream. |
![]() ![]() | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) |
![]() | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) |
![]() | ObjectInvariant | Infrastructure. Provides support for a Contract. (Inherited from Stream.) |
![]() ![]() | Read | Reads a block of bytes from the stream and writes the data in a given buffer. (Overrides Stream.Read(Byte(), Int32, Int32).) |
![]() ![]() | ReadByte | Reads a byte from the file and advances the read position one byte. (Overrides Stream.ReadByte.) |
![]() ![]() | Seek | Sets the current position of this stream to the given value. (Overrides Stream.Seek(Int64, SeekOrigin).) |
![]() | SetAccessControl | Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object. |
![]() ![]() | SetLength | Sets the length of this stream to the given value. (Overrides Stream.SetLength(Int64).) |
![]() ![]() | ToString | Returns a string that represents the current object. (Inherited from Object.) |
![]() | Unlock | Allows access by other processes to all or part of a file that was previously locked. |
![]() ![]() | Write | Writes a block of bytes to this stream using data from a buffer. (Overrides Stream.Write(Byte(), Int32, Int32).) |
![]() ![]() | WriteByte | Writes a byte to the current position in the file stream. (Overrides Stream.WriteByte(Byte).) |
Use the FileStream class to read from, write to, open, and close files on a file system, as well as to manipulate other file-related operating system handles including pipes, standard input, and standard output. You can specify read and write operations to be either synchronous or asynchronous. FileStream buffers input and output for better performance.
FileStream objects support random access to files using the Seek method. 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 properties of the SeekOrigin class.
Note |
|---|
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. Specifically, 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. |
Although the synchronous methods Read and Write and the asynchronous methods BeginRead, BeginWrite, EndRead, and EndWrite can work in either synchronous or asynchronous mode, the mode affects the performance of these methods. FileStream defaults to opening files synchronously, but provides the FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) constructor to open files asynchronously.
If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
For directory and other file operations, see the File, Directory, and Path classes. The File class is a utility class with static methods primarily for the creation of FileStream objects based on file paths and the standard input, standard output, and standard error devices. The MemoryStream class creates a stream from a byte array and functions similarly to a FileStream.
For a list of common I/O tasks, 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 assure 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 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 opens a file or creates it if it does not already exist, and appends information to the end of the file.
Imports System Imports System.IO Imports System.Text Class FSOpenWrite Public Shared Sub Main() Dim fs As New FileStream("c:\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write) fs.Close() Dim sw As New StreamWriter("c:\Variables.txt", True, Encoding.ASCII) Dim NextLine As String = "This is the appended text." sw.Write(NextLine) sw.Close() End Sub 'Main End Class 'FSOpenWrite
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
