public class FileStream : Stream
|
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.
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.
ctor #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: Gets a value indicating whether the current stream supports reading. |
CanSeek | Read-only Overridden: Gets a value indicating whether the current stream supports seeking. |
CanWrite | Read-only Overridden: Gets a value indicating whether the current stream supports writing. |
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: Gets the length in bytes of the stream. |
Name | Read-only Gets the name of the FileStream that was passed to the constructor. |
Position | Read-write Overridden: Gets or sets the current position of this stream. |
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. |
CreateWaitHandle (inherited from System.IO.Stream) |
See base class member description: System.IO.Stream.CreateWaitHandle Allocates a WaitHandle object. |
Dispose | Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. |
Finalize | Overridden: Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public FileStream( |
handle
access
Exception Type | Condition |
---|---|
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.
path
mode
Exception Type | Condition |
---|---|
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).
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.
public FileStream( |
handle
access
ownsHandle
Exception Type | Condition |
---|---|
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.
public FileStream( |
path
mode
access
Exception Type | Condition |
---|---|
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).
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.
public FileStream( |
handle
access
ownsHandle
bufferSize
Exception Type | Condition |
---|---|
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.
public FileStream( |
path
mode
access
share
Exception Type | Condition |
---|---|
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).
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.
public FileStream( |
handle
access
ownsHandle
bufferSize
isAsync
Exception Type | Condition |
---|---|
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.
public FileStream( |
path
mode
access
share
bufferSize
Exception Type | Condition |
---|---|
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.
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.
public FileStream( |
path
mode
access
share
bufferSize
useAsync
Exception Type | Condition |
---|---|
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.
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.
public override bool CanRead {get;}
|
If the stream is closed, this property returns false.
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.
public override bool CanSeek {get;}
|
If the stream is closed, this property returns false.
public override bool CanWrite {get;}
|
If the stream is closed, this property returns false.
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.
public virtual IntPtr Handle {get;}
|
Exception Type | Condition |
---|---|
SecurityException | 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.
public virtual bool IsAsync {get;}
|
public override long Length {get;}
|
Exception Type | Condition |
---|---|
NotSupportedException | FileStream.CanSeek for this stream is false. |
IOException | An I/O error occurs, such as the file being closed. |
if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }
public string Name {get;}
|
public override long Position {get; set;}
|
Exception Type | Condition |
---|---|
NotSupportedException | 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.
if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }
public override IAsyncResult BeginRead( |
array
offset
numBytes
userCallback
stateObject
Exception Type | Condition |
---|---|
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. |
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.
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.
public override IAsyncResult BeginWrite( |
array
offset
numBytes
userCallback
stateObject
Exception Type | Condition |
---|---|
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.
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.
public override void Close(); |
Exception Type | Condition |
---|---|
IOException | 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.
requestedType
Exception Type | Condition |
---|---|
RemotingException | This instance is not a valid remoting object. |
protected virtual WaitHandle CreateWaitHandle(); |
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.
protected virtual void Dispose( |
disposing
public override int EndRead( |
asyncResult
Exception Type | Condition |
---|---|
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.
public override void EndWrite( |
asyncResult
Exception Type | Condition |
---|---|
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.
~FileStream(); |
Exception Type | Condition |
---|---|
IOException | The handle for the file is invalid. |
public override void Flush(); |
Exception Type | Condition |
---|---|
IOException | 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:
public virtual int GetHashCode(); |
public object GetLifetimeService(); |
public Type GetType(); |
public virtual object InitializeLifetimeService(); |
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; } }
position
length
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | position or length is negative. |
IOException | An I/O error occurs, such as the file being closed or its handle being invalid. |
protected object MemberwiseClone(); |
array
offset
count
Exception Type | Condition |
---|---|
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.
if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }
public override int ReadByte(); |
Exception Type | Condition |
---|---|
NotSupportedException | The current stream does not support reading. |
ObjectDisposedException | The current stream is closed. |
public override long Seek(long offset, Seek( |
offset
origin
Exception Type | Condition |
---|---|
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. |
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.
public override void SetLength( |
value
Exception Type | Condition |
---|---|
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.
public virtual string ToString(); |
position
length
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | position or length is negative. |
array
offset
count
Exception Type | Condition |
---|---|
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.
public override void WriteByte( |
value
Exception Type | Condition |
---|---|
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.