FileStream is used for reading and writing files on a file system, as well as other file-related operating system handles such as pipes, standard input, standard output. FileStream buffers input and output for better performance.
The FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods [System.IO.FileStream.Read[System.Byte[],System.Int32,System.Int32] and System.IO.FileStream.Write[System.Byte[],System.Int32,System.Int32]] and the asynchronous methods [System.IO.FileStream.BeginRead[System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object] and System.IO.FileStream.BeginWrite[System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object] ]. Both sets of methods will work in either mode; however, the mode will affect the performance of these methods. FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously.
When accessing files, a security check is performed when the file is created or opened. The security check is typically not done again unless the file is closed and reopened. [Note: Checking permissions when the file is first accessed minimizes the impact of the security check on application performance [since opening a file happens once, while reading and writing can happen multiple times].]
Note that if an opened file is passed to an untrusted caller, the security system can, but is not required to prevent the caller from accessing the file.
FileStream objects support random access to files using the System.IO.FileStream.Seek[System.Int64,System.IO.SeekOrigin] method, and the System.IO.Stream.CanSeek properties of FileStream instances encapsulating files are set to true . The System.IO.FileStream.Seek[System.Int64,System.IO.SeekOrigin] method 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 values of the SeekOrigin enumeration.
If a FileStream encapsulates a device that does not support seeking, its System.IO.FileStream.CanSeek property is false . [Note: For additional information, see System.IO.Stream.CanSeek.]
[Note: The File class provides methods for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and functions similarly to a FileStream.]
The following example demonstrates the use of a FileStream object.using System; using System.IO; class Directory { public static void Main[String[] args] { FileStream fs = new FileStream["log.txt", FileMode.OpenOrCreate, FileAccess.Write]; StreamWriter w = new StreamWriter[fs]; w.BaseStream.Seek[0, SeekOrigin.End]; // Set the file pointer to the end. Log ["Test1", w]; Log ["Test2", w]; w.Close[]; // Close the writer and underlying file. fs = new FileStream["log.txt", FileMode.OpenOrCreate, FileAccess.Read]; StreamReader r = new StreamReader[fs]; r.BaseStream.Seek[0, SeekOrigin.Begin]; DumpLog [r]; } public static void Log [String logMessage, StreamWriter w] { w.Write["Log Entry : "]; w.WriteLine["{0} {1}", DateTime.Now.ToLongTimeString[], DateTime.Now.ToLongDateString[]]; w.WriteLine[":"]; w.WriteLine[":{0}", logMessage]; w.WriteLine ["-------------------------------"]; w.Flush[]; } public static void DumpLog [StreamReader r] { while [r.Peek[] > -1] { // While not at the end of the file, write to standard output. Console.WriteLine[r.ReadLine[]]; } r.Close[]; } } Some example output is
Log Entry : 9:26:21 AM Friday, July 06, 2001
:
:Test1
-------------------------------
Log Entry : 9:26:21 AM Friday, July 06, 2001
:
:Test2
-------------------------------
Assembly: Mscorlib.dllNamespace: System.IO
Summary Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.C# Syntax:
public class FileStream : Stream
RemarksFileStream is useful for reading and writing files on a file system, as well as other file-related operating system handles [including pipes, standard input, standard output, and so on].FileStream buffers input and output for better performance.The FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods [ FileStream.Read and FileStream.Write] and the asynchronous methods [ FileStream.BeginRead and FileStream.BeginWrite]. Both sets of methods will work in either mode; however, the mode will affect the performance of these methods.FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously.
For file and directory 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.
If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
ExampleFileStream objects support random access to files using the FileStream.Seek method. The Seek method 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 FileStream.CanSeek property 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 is true. Otherwise, the CanSeek property is false.
In the following example, a file is opened, or created if it does not already exist, and information is appended to the end of the file. The contents of the file are then written to standard output for display.
See also: System.IO Namespace | File | FileAccess | FileMode | FileShareSystem.IO.FileStream Member List:
Public�Constructorsctor #1 | Overloaded: .ctor[IntPtr handle, FileAccess access] Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
ctor #2 | Overloaded: .ctor[string path, FileMode mode] Initializes a new instance of the FileStream class with the specified path and creation mode. |
ctor #3 | Overloaded: .ctor[IntPtr handle, FileAccess access, bool ownsHandle] Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership. |
ctor #4 | Overloaded: .ctor[string path, FileMode mode, FileAccess access] Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission. |
ctor #5 | Overloaded: .ctor[IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize] 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. |
ctor #6 | Overloaded: .ctor[string path, FileMode mode, FileAccess access, FileShare share] Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission. |
ctor #7 | Overloaded: .ctor[IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync] 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. |
ctor #8 | Overloaded: .ctor[string path, FileMode mode, FileAccess access, FileShare share, int bufferSize] Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size. |
ctor #9 | Overloaded: .ctor[string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync] 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. |
CanRead | Read-only Overridden: |
CanSeek | Read-only Overridden: |
CanWrite | Read-only Overridden: |
Handle | Read-only Gets the operating system file handle for the file that the current FileStream object encapsulates. |
IsAsync | Read-only Gets a value indicating whether the FileStream was opened asynchronously or synchronously. |
Length | Read-only Overridden: |
Name | Read-only Gets the name of the FileStream that was passed to the constructor. |
Position | Read-write Overridden: |
BeginRead | Overridden: Begins an asynchronous read. |
BeginWrite | Overridden: Begins an asynchronous write. |
Close | Overridden: Closes the file and releases any resources associated with the current file stream. |
CreateObjRef [inherited from�System.MarshalByRefObject] | See base class member description: System.MarshalByRefObject.CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. |
EndRead | Overridden: Waits for the pending asynchronous read to complete. |
EndWrite | Overridden: Ends an asynchronous write, blocking until the I/O operation has completed. |
Equals [inherited from�System.Object] | See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
Flush | Overridden: Clears all buffers for this stream and causes any buffered data to be written to the underlying device. |
GetHashCode [inherited from�System.Object] | See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetLifetimeService [inherited from�System.MarshalByRefObject] | See base class member description: System.MarshalByRefObject.GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. |
GetType [inherited from�System.Object] | See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
InitializeLifetimeService [inherited from�System.MarshalByRefObject] | See base class member description: System.MarshalByRefObject.InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. |
Lock | Prevents access by other processes to all or part of a file. |
Read | Overridden: Reads a block of bytes from the stream and writes the data in a given buffer. |
ReadByte | Overridden: Reads a byte from the file and advances the read position one byte. |
Seek | Overridden: Sets the current position of this stream to the given value. |
SetLength | Overridden: Sets the length of this stream to the given value. |
ToString [inherited from�System.Object] | See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
Unlock | Allows access by other processes to all or part of a file that was previously locked. |
Write | Overridden: Writes a block of bytes to this stream using data from a buffer. |
WriteByte | Overridden: Writes a byte to the current position in the file stream. |
Hierarchy:
- System.Object
- System.MarshalByRefObject
- System.IO.Stream
- System.IO.FileStream
- System.IO.IsolatedStorage.IsolatedStorageFileStream
System.IO.FileStream Member Details
Overloaded ctor #1Summary Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.C# Syntax:Parameters:handle
access
ArgumentException | access is not a field of FileAccess. |
SecurityException | The caller does not have the required permission. |
IOException | An I/O error occurs, such as a disk error. |
UnauthorizedAccessException | The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access. |
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
.NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #2Summary Initializes a new instance of the FileStream class with the specified path and creation mode.C# Syntax:Parameters:path
mode
ArgumentException | path is an empty string [""]. |
ArgumentNullException | path is null. |
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 directory path leading to the file specified by path does not exist. |
PathTooLongException | The specified path, file name, or both are too long. After full qualification, each must be less than 256 characters. |
ArgumentOutOfRangeException | mode contains an invalid value. |
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, in C#, C++, or JScript code, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt.
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 8192 bytes [8 KB].
Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.
Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek.
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
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..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.See also:Path.InvalidPathChars
Return to top
Overloaded ctor #3Summary Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.C# Syntax:Parameters:handle
access
ownsHandle
ArgumentException | access is not a field of FileAccess. |
SecurityException | The caller does not have the required permission. |
IOException | An I/O error occurs, such as a disk error. |
UnauthorizedAccessException | The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access. |
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling methods other than Close after you are done using the handle.
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #4Summary Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.C# Syntax:Parameters:path
mode
access
ArgumentNullException | path is null. |
ArgumentException | path is an empty string [""]. |
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 directory path leading to the file specified by path does not exist. |
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 are too long. After full qualification, each must be less than 256 characters. |
ArgumentOutOfRangeException | mode contains an invalid value. |
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt.
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 8192 bytes [8 KB].
Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.
Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek.
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #5Summary 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.C# Syntax:Parameters:handle
access
ownsHandle
bufferSize
ArgumentOutOfRangeException | bufferSize is negative. |
IOException | An I/O error occurs, such as a disk error. |
SecurityException | The caller does not have the required permission. |
UnauthorizedAccessException | The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access. |
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #6Summary Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.C# Syntax:Parameters:path
mode
access
share
ArgumentNullException | path is null. |
ArgumentException | path is an empty string [""]. |
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 directory path leading to the file specified by path does not exist. |
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 are too long. After full qualification, each must be less than 256 characters. |
ArgumentOutOfRangeException | mode contains an invalid value. |
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt.
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 8192 bytes [8 KB].
Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.
Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #7Summary 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.C# Syntax:Parameters:handle
access
ownsHandle
bufferSize
isAsync
ArgumentOutOfRangeException | access is less than FileAccess.Read or greater than FileAccess.ReadWrite or bufferSize is less than or equal to 0. |
ArgumentException | The handle is invalid. |
IOException | An I/O error occurs, such as a disk error. |
SecurityException | The caller does not have the required permission. |
UnauthorizedAccessException | The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access. |
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor.
FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: SecurityPermission for access to unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.Return to top
Overloaded ctor #8Summary Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.C# Syntax:Parameters:path
mode
access
share
bufferSize
ArgumentNullException | path is null. |
ArgumentException | path is an empty string [""]. |
ArgumentOutOfRangeException | bufferSize is negative. -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 directory path leading to the file specified by path does not exist. |
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 are too long. After full qualification, each must be less than 256 characters. |
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt.
Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.
Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to top
Overloaded ctor #9Summary 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.C# Syntax:Parameters:path
mode
access
share
bufferSize
useAsync
ArgumentNullException | path is null. |
ArgumentException | path is an empty string [""]. |
ArgumentOutOfRangeException | bufferSize is negative. -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 directory path leading to the file specified by path does not exist. |
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 are too long. After full qualification, each must be less than 256 characters. |
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt.
Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.
Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek.
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.See also:File
Return to top
Overridden Property: CanRead [read-only]Summary Gets a value indicating whether the current stream supports reading.C# Syntax:
public override bool�CanRead {get;}
Remarks If a class derived from Stream does not support reading, calls to the FileStream.Read, FileStream.ReadByte, FileStream.BeginRead, and FileStream.EndRead methods throw a NotSupportedException.If the stream is closed, this property returns false.
Example The following is an example of using the CanRead property. using System; using System.IO; class TestRW { public static void Main[String[] args] { FileStream fs = new FileStream["MyFile.txt", FileMode.OpenOrCreate, FileAccess.Read]; if [fs.CanRead && fs.CanWrite] { Console.WriteLine["MyFile.txt can be both written to and read from."]; } else if [fs.CanRead] { Console.WriteLine["MyFile.txt is not writable."]; } } } //This code outputs "MyFile.txt is not writable." //To get the output message "MyFile.txt can be both written to and read from.", //change the FileAccess parameter to ReadWrite in the FileStream constructor.Return to top
Overridden Property: CanSeek [read-only]Summary Gets a value indicating whether the current stream supports seeking.C# Syntax:
public override bool�CanSeek {get;}
Remarks If a class derived from Stream does not support seeking, calls to FileStream.Length, FileStream.SetLength, FileStream.Position, and FileStream.Seek throw a NotSupportedException.If the stream is closed, this property returns false.
Return to top
Overridden Property: CanWrite [read-only]Summary Gets a value indicating whether the current stream supports writing.C# Syntax:
public override bool�CanWrite {get;}
Remarks If a class derived from Stream does not support writing, a call to FileStream.SetLength, FileStream.Write, FileStream.BeginWrite, FileStream.EndWrite, or FileStream.WriteByte throws a NotSupportedException.If the stream is closed, this property returns false.
Example The following is an example using the CanWrite property. using System; using System.IO; class TestRW { public static void Main[String[] args] { FileStream fs = new FileStream["MyFile.txt", FileMode.OpenOrCreate, FileAccess.Write]; if [fs.CanRead && fs.CanWrite] { Console.WriteLine["MyFile.txt can be both written to and read from."]; } else if [fs.CanWrite] { Console.WriteLine["MyFile.txt is writable."]; } } } //This code outputs "MyFile.txt is writable." //To get the output message "MyFile.txt can be both written to and read from.", //change the FileAccess parameter to ReadWrite in the FileStream constructor.Return to top
Property: Handle [read-only]Summary Gets the operating system file handle for the file that the current FileStream object encapsulates.C# Syntax:
public virtual IntPtr�Handle {get;}
ExceptionsSecurityException | The caller does not have the required permission. |
The operating system handle might have been opened synchronously or asynchronously, depending on which FileStream constructor was called. Use the FileStream.IsAsync property to discover whether this handle was opened asynchronously. In Win32, this means the handle was opened for overlapped IO, and it requires different parameters to ReadFile and WriteFile.
Data corruption might occur if a FileStream is created, its handle is passed, some operation moves the handle's file pointer, and then the FileStream is used again. Multiple threads cannot safely write to the same file simultaneously, and FileStream buffering code assumes that it exclusively controls the handle.FileStream might throw an IOException if FileStream detects that some other process has moved the file pointer. To avoid this, do not write any data into a portion of the file that FileStream might have buffered, and restore the file pointer to the location it had when methods were last called on FileStream..NET Framework Security: SecurityPermission for calling unmanaged code, such as calling native code with PInvoke or COM integration. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.Return to top
Property: IsAsync [read-only]Summary Gets a value indicating whether the FileStream was opened asynchronously or synchronously.C# Syntax:
public virtual bool�IsAsync {get;}
Remarks The IsAsync property detects whether the FileStream handle was opened asynchronously, enabling your code to use the FileStream.Handle property correctly. In Win32, IsAsync being true means the handle was opened for overlapped I/O, and thus requires different parameters to ReadFile and WriteFile.Return to top
Overridden Property: Length [read-only]Summary Gets the length in bytes of the stream.C# Syntax:
public override long�Length {get;}
ExceptionsNotSupportedException | FileStream.CanSeek for this stream is false. |
IOException | An I/O error occurs, such as the file being closed. |
Return to top
Property: Name [read-only]Summary Gets the name of the FileStream that was passed to the constructor.C# Syntax:.NET Framework Security: FileIOPermission for access to the path. Associated enumeration: FileIOPermissionAccess.PathDiscovery
Return to top
Overridden Property: Position [read-write]Summary Gets or sets the current position of this stream.C# Syntax:
public override long�Position {get; set;}
ExceptionsNotSupportedException | The stream does not support seeking. |
IOException | An I/O error occurs. |
ArgumentOutOfRangeException | Attempted to set the position to a negative value. |
EndOfStreamException | Attempted seeking past the end of a stream that does not support this. |
In order to open a new file and write to it, set the position to one byte beyond the end of the stream. This allows you to append to the file. The position cannot be set to more than one byte beyond the end of the stream.
Example The following is an example of using the Length and Position properties to check for an end-of-file condition. if[ s.Length==s.Position ] { Console.WriteLine["End of file has been reached."]; }Return to top
Overridden Method: BeginRead[���byte[]�array,
���int�offset,
���int�numBytes,
���AsyncCallback�userCallback,
���object�stateObject
]Summary Begins an asynchronous read.C# Syntax:Parameters:
array
offset
numBytes
userCallback
stateObject
ArgumentException | The array length minus offset is less than numBytes. |
ArgumentNullException | array is null. |
ArgumentOutOfRangeException | offset or numBytes is negative. |
IOException | An asynchronous read was attempted past the end of the file. |
Note Use the FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see Stream.CanRead.
If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginRead. Errors that occur during an asynchronous read request, such as a disk failure during the IO request, occur on the threadpool thread and become visible upon a call to FileStream.EndRead.
Note On Windows, all I/O operations smaller than 64 KB will complete synchronously for better performance. Asynchronous I/O might hinder performance for buffer sizes smaller than 64 KB.
Stream.EndRead must be called with this IAsyncResult to find out how many bytes were read.
Multiple simultaneous asynchronous requests render the request completion order uncertain.
Return to top
Overridden Method: BeginWrite[���byte[]�array,
���int�offset,
���int�numBytes,
���AsyncCallback�userCallback,
���object�stateObject
]Summary Begins an asynchronous write.C# Syntax:Parameters:
array
offset
numBytes
userCallback
stateObject
ArgumentException | array length minus offset is less than numBytes. |
ArgumentNullException | array is null. |
ArgumentOutOfRangeException | offset or numBytes is negative. |
IOException | The stream does not support writing, or an I/O error occurs. |
FileStream provides two different modes of operation: synchronous I/O and asynchronous I/O. While either can be used, the underlying operating system resources might allow access in only one of these modes. By default, FileStream opens the operating system handle synchronously. In Windows, this slows down asynchronous methods. If asynchronous methods are used, call the FileStream constructor that has the isAsync parameter.
If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginWrite. Errors that occur during an asynchronous write request, such as a disk failure during the IO request, occur on the threadpool thread and become visible upon a call to FileStream.EndWrite.
Note On Windows, all I/O operations smaller than 64 KB will complete synchronously for better performance. Asynchronous I/O might hinder performance for buffer sizes smaller than 64 KB.
Stream.EndWrite must be called with this IAsyncResult to find out how many bytes were read.
Multiple simultaneous asynchronous requests render the request completion order uncertain.
Return to top
Overridden Method: Close[]Summary Closes the file and releases any resources associated with the current file stream.C# Syntax:public override void Close[];
ExceptionsIOException | An error occurred while trying to close the stream. |
This implementation of Close calls the FileStream.Dispose method passing a true value.
Any data previously written to the buffer is copied to the file before the file stream is closed, so it is not necessary to call FileStream.Flush before invoking Close. Following a call to Close, any operations on the file stream might raise exceptions. After Close has been called once, it does nothing if called again.
Flushing the stream will not flush its underlying encoder unless you explicitly call FileStream.Flush or Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state [partial characters] so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.
The FileStream.Finalize method invokes Close so that the file stream is closed before the garbage collector finalizes the object. However, objects writing to the FileStream, such as a StreamWriter, might not have flushed the data from their internal buffers to the FileStream when the call to Finalize closes the stream. To prevent data loss, always call Close on the highest-level object.
If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
Note This version of Close is equivalent to Dispose.
Return to top
Method: CreateObjRef[���Type�requestedType
] Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef
Summary Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.C# Syntax:
public virtual ObjRef�CreateObjRef[
���Type�requestedType
];
requestedType
RemotingException | This instance is not a valid remoting object. |
Return to top
Method: CreateWaitHandle[] InheritedSee base class member description: System.IO.Stream.CreateWaitHandle
Summary Allocates a WaitHandle object.C# Syntax:Return Value: A reference to the allocated WaitHandle. Remarks When called for the first time, the current method creates a WaitHandle object and returns it. On subsequent calls, the CreateWaitHandle returns a reference to the same wait handle.
Use this method if you implement the asynchronous methods and require a way of blocking in Stream.EndRead or Stream.EndWrite until the asynchronous operation is complete.
Return to top
Method: Dispose[���bool�disposing
]Summary Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.C# Syntax:
protected virtual void Dispose[
���bool�disposing
];
disposing
Notes to inheritors: FileStream.Dispose may be called multiple times by other objects. When overriding FileStream.Dispose, be careful not to reference objects that have been previously disposed in an earlier call to FileStream.Dispose. This method calls the dispose method of the base class, IDisposable.Dispose.
Return to top
Overridden Method: EndRead[���IAsyncResult�asyncResult
]Summary Waits for the pending asynchronous read to complete.C# Syntax:Parameters:
asyncResult
ArgumentNullException | asyncResult is null. |
ArgumentException | This IAsyncResult object was not created by calling FileStream.BeginRead on this class. |
InvalidOperationException | EndRead is called multiple times. |
EndRead can be called on every IAsyncResult from FileStream.BeginRead. Calling EndRead tells you how many bytes were read from the stream.EndRead will block until the I/O operation has completed.
Return to top
Overridden Method: EndWrite[���IAsyncResult�asyncResult
]Summary Ends an asynchronous write, blocking until the I/O operation has completed.C# Syntax:Parameters:
asyncResult
ArgumentNullException | asyncResult is null. |
ArgumentException | This IAsyncResult object was not created by calling Stream.BeginWrite on this class. |
InvalidOperationException | EndWrite is called multiple times. |
EndWrite must be called exactly once on every IAsyncResult from FileStream.BeginWrite.EndWrite will block until the I/O operation has completed.
Return to top
Method: Equals[���object�obj
] Inherited
See base class member description: System.Object.Equals C# Syntax:
For more information on members inherited from System.Object click on the link above.
Return to top
Overridden Method: Finalize[]Summary Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.C# Syntax:ExceptionsIOException | The handle for the file is invalid. |
Return to top
Overridden Method: Flush[]Summary Clears all buffers for this stream and causes any buffered data to be written to the underlying device.C# Syntax:public override void Flush[];
ExceptionsIOException | An I/O error occurs. |
ObjectDisposedException | The stream is closed. |
Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or FileStream.Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state [partial characters] so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.
Because a buffer can be used for either reading or writing, Flush performs the following two functions:
- Any data previously written to the buffer is copied to the file and the buffer is cleared except for its encoder state.
- If BufferedStream.CanSeek is true and data was previously copied from the file to the buffer for reading, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared.
Return to top
Method: GetHashCode[] InheritedSee base class member description: System.Object.GetHashCodeC# Syntax:
public virtual int�GetHashCode[];
For more information on members inherited from System.Object click on the link above.
Return to top
Method: GetLifetimeService[] InheritedSee base class member description: System.MarshalByRefObject.GetLifetimeService
Summary Retrieves the current lifetime service object that controls the lifetime policy for this instance.C# Syntax:
public object�GetLifetimeService[];
Return Value: An object of type ILease used to control the lifetime policy for this instance.Remarks For more information about lifetime services, see the LifetimeServices class.Return to top
Method: GetType[] InheritedSee base class member description: System.Object.GetTypeC# Syntax:
For more information on members inherited from System.Object click on the link above.
Return to top
Method: InitializeLifetimeService[] InheritedSee base class member description: System.MarshalByRefObject.InitializeLifetimeService
Summary Obtains a lifetime service object to control the lifetime policy for this instance.C# Syntax:
public virtual object�InitializeLifetimeService[];
Return Value: An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.Remarks For more information about lifetime services, see the LifetimeServices class.Example The following code example demonstrates creating a lease. public class MyClass : MarshalByRefObject { public override Object InitializeLifetimeService[] { ILease lease = [ILease]base.InitializeLifetimeService[]; if [lease.CurrentState == LeaseState.Initial] { lease.InitialLeaseTime = TimeSpan.FromMinutes[1]; lease.SponsorshipTimeout = TimeSpan.FromMinutes[2]; lease.RenewOnCallTime = TimeSpan.FromSeconds[2]; } return lease; } }Return to top
Method: Lock[���long�position,
���long�length
]Summary Prevents access by other processes to all or part of a file.C# Syntax:
public virtual void Lock[
���long�position,
���long�length
];
position
length
ArgumentOutOfRangeException | position or length is negative. |
IOException | An I/O error occurs, such as the file being closed or its handle being invalid. |
Return to top
Method: MemberwiseClone[] InheritedSee base class member description: System.Object.MemberwiseCloneC# Syntax:
protected object�MemberwiseClone[];
For more information on members inherited from System.Object click on the link above.
Return to top
Overridden Method: Read[���in�byte[] array,
���int�offset,
���int�count
]Summary Reads a block of bytes from the stream and writes the data in a given buffer.C# Syntax:
public override int�Read[
���in�byte[] array,
���int�offset,
���int�count
];
array
offset
count
ArgumentNullException | array is null. |
ArgumentOutOfRangeException | offset or count is negative. |
NotSupportedException | The stream does not support reading. |
IOException | An I/O error occurs. |
ArgumentException | offset and count describe an invalid range in array. |
ObjectDisposedException | Methods were called after the stream was closed. |
The offset parameter gives the offset of the byte in array [the buffer index] at which to begin writing, and the count parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged.
The Read method returns zero only after reaching the end of the stream. Otherwise, Read always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to Read, the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.
Use BinaryReader for reading primitive data types.
Example The following is an example of using the Length and Position properties to check for an end-of-file condition. if[ s.Length==s.Position ] { Console.WriteLine["End of file has been reached."]; }Return to top
Overridden Method: ReadByte[]Summary Reads a byte from the file and advances the read position one byte.C# Syntax:public override int�ReadByte[];
Return Value: The byte cast to an int, or -1 if reading from the end of the stream.ExceptionsNotSupportedException | The current stream does not support reading. |
ObjectDisposedException | The current stream is closed. |
Note Use the FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see Stream.CanRead.
Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Read. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.
Return to top
Overridden Method: Seek[���long�offset,
���SeekOrigin�origin
]Summary Sets the current position of this stream to the given value.C# Syntax:Parameters:
offset
origin
IOException | An I/O error occurs. |
NotSupportedException | The stream does not support seeking, such as if the FileStream is constructed from a pipe or console output. |
ArgumentException | Attempted seeking before the beginning of the stream or more than one byte past the end of the stream. |
ObjectDisposedException | Methods were called after the stream was closed. |
Note Use the FileStream.CanSeek property to determine whether the current instance supports seeking. For additional information, see Stream.CanSeek.
Seeking to any location beyond the length of the stream is supported.
In order to open a new file and write to it, set the position to one byte beyond the end of the stream. This allows you to append to the file. The position cannot be set to more than one byte beyond the end of the stream.
On some platforms, seeking past the end of a file and then doing a write operation results in undefined behavior.
Return to top
Overridden Method: SetLength[���long�value
] Summary Sets the length of this stream to the given value.C# Syntax:
public override void SetLength[
���long�value
];
value
IOException | An I/O error has occurred. |
NotSupportedException | The stream does not support both writing and seeking. |
ArgumentOutOfRangeException | Attempted to set the value parameter to less than 0. |
If the given value is less than the current length of the stream, the stream is truncated. If the given value is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are undefined.
A stream must support both writing and seeking for SetLength to work.
Note Use the FileStream.CanWrite property to determine whether the current instance supports writing, and the FileStream.CanSeek property to determine whether seeking is supported. For additional information, see Stream.CanWrite and Stream.CanSeek.
Return to top
Method: ToString[] InheritedSee base class member description: System.Object.ToStringC# Syntax:
public virtual string ToString[];
For more information on members inherited from System.Object click on the link above.
Return to top
Method: Unlock[���long�position,
���long�length
]Summary Allows access by other processes to all or part of a file that was previously locked.C# Syntax:
public virtual void Unlock[
���long�position,
���long�length
];
position
length
ArgumentOutOfRangeException | position or length is negative. |
Return to top
Overridden Method: Write[���byte[]�array,
���int�offset,
���int�count
]Summary Writes a block of bytes to this stream using data from a buffer.C# Syntax:
public override void Write[
���byte[]�array,
���int�offset,
���int�count
];
array
offset
count
ArgumentNullException | array is null. |
ArgumentException | offset and count describe an invalid range in array. |
ArgumentOutOfRangeException | offset or count is negative. |
IOException | An I/O error occurs. |
NotSupportedException | The current stream instance does not support writing. |
The offset parameter gives the offset of the byte in array [the buffer index] at which to begin reading, and the count parameter gives the maximum number of bytes that will be written to this stream. If the write operation is successful, the current position of the stream is advanced by the number of bytes written. If an exception occurs, the current position of the stream is unchanged.
Note Use the FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see Stream.CanWrite.
Return to top
Overridden Method: WriteByte[���byte�value
]Summary Writes a byte to the current position in the file stream.C# Syntax:
public override void WriteByte[
���byte�value
];
value
IOException | The stream is closed. |
NotSupportedException | The stream does not support writing, or the stream is already closed. |
Use WriteByte to write a byte to a FileStream efficiently. If the stream is closed or not writable, an exception will be thrown.
Note Use the FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see Stream.CanWrite.
Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Write. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.