System.IO.FileStream Class

Assembly: Mscorlib.dll
Namespace: System.IO
Summary
Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
C# Syntax:
public class FileStream : Stream
Remarks
FileStream 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.

Example
FileStream 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 | FileShare

System.IO.FileStream Member List:

Public Constructors
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.
Public Properties
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.
Public Methods
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.
Protected Methods
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:


System.IO.FileStream Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
C# Syntax:
public FileStream(
   IntPtr handle,
   FileAccess access
);
Parameters:

handle

A file handle for the file that the current FileStream object will encapsulate.

access

A FileAccess constant that gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object.

Exceptions
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.
Remarks
When FileStream.Close is called, the handle is also closed and the file's handle count is decremented.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. 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.

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 #2
Summary
Initializes a new instance of the FileStream class with the specified path and creation mode.
C# Syntax:
public FileStream(
   string path,
   FileMode mode
);
Parameters:

path

A relative or absolute path for the file that the current FileStream object will encapsulate.

mode

A FileMode constant that determines how to open or create the file.

Exceptions
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.
Remarks
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

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 #3
Summary
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:
public FileStream(
   IntPtr handle,
   FileAccess access,
   bool ownsHandle
);
Parameters:

handle

A file handle for the file that the current FileStream object will encapsulate.

access

A FileAccess constant that gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object.

ownsHandle

true if the file handle will be owned by this FileStream instance; otherwise, false.

Exceptions
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.
Remarks
The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this process owns the handle, a call to the FileStream.Close method will also close the handle and the file's handle count is decremented. The FileStream object is given the default buffer size of 8192 bytes.

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 #4
Summary
Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.
C# Syntax:
public FileStream(
   string path,
   FileMode mode,
   FileAccess access
);
Parameters:

path

A relative or absolute path for the file that the current FileStream object will encapsulate.

mode

A FileMode constant that determines how to open or create the file.

access

A FileAccess constant that determines how the file may be accessed by the FileStream object. This gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object. FileStream.CanSeek is true if path specifies a disk file.

Exceptions
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.
Remarks
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

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 #5
Summary
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:
public FileStream(
   IntPtr handle,
   FileAccess access,
   bool ownsHandle,
   int bufferSize
);
Parameters:

handle

A file handle for the file that this FileStream object will encapsulate.

access

A FileAccess constant that gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object.

ownsHandle

true if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize

The size of the buffer in bytes.

Exceptions
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.
Remarks
The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the FileStream.Close method will also close the handle. In particular, the file's handle count is decremented. The FileStream object is given the specified buffer size.

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 #6
Summary
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.
C# Syntax:
public FileStream(
   string path,
   FileMode mode,
   FileAccess access,
   FileShare share
);
Parameters:

path

A relative or absolute path for the file that the current FileStream object will encapsulate.

mode

A FileMode constant that determines how to open or create the file.

access

A FileAccess constant that determines how the file may be accessed by the FileStream object. This gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object. FileStream.CanSeek is true if path specifies a disk file.

share

A FileShare constant that determines how the file will be shared by processes.

Exceptions
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.
Remarks
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

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 #7
Summary
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:
public FileStream(
   IntPtr handle,
   FileAccess access,
   bool ownsHandle,
   int bufferSize,
   bool isAsync
);
Parameters:

handle

A file handle for the file that this FileStream object will encapsulate.

access

A FileAccess constant that gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object.

ownsHandle

true if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize

The size of the buffer in bytes.

isAsync

true if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false.

Exceptions
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.
Remarks
The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the FileStream.Close method will also close the handle. In particular, the file's handle count is decremented. The FileStream object is given the specified buffer size.

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 #8
Summary
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.
C# Syntax:
public FileStream(
   string path,
   FileMode mode,
   FileAccess access,
   FileShare share,
   int bufferSize
);
Parameters:

path

A relative or absolute path for the file that the current FileStream object will encapsulate.

mode

A FileMode constant that determines how to open or create the file.

access

A FileAccess constant that determines how the file may be accessed by the FileStream object. This gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object. FileStream.CanSeek is true if path specifies a disk file.

share

A FileShare constant that determines how the file will be shared by processes.

bufferSize

The desired buffer size in bytes. For bufferSize values between zero and eight, the actual buffer size is set to eight bytes.

Exceptions
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.
Remarks
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

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 #9
Summary
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:
public FileStream(
   string path,
   FileMode mode,
   FileAccess access,
   FileShare share,
   int bufferSize,
   bool useAsync
);
Parameters:

path

A relative or absolute path for the file that the current FileStream object will encapsulate.

mode

A FileMode constant that determines how to open or create the file.

access

A FileAccess constant that determines how the file may be accessed by the FileStream object. This gets the FileStream.CanRead and FileStream.CanWrite properties of the FileStream object. FileStream.CanSeek is true if path specifies a disk file.

share

A FileShare constant that determines how the file will be shared by processes.

bufferSize

The desired buffer size in bytes. For bufferSize values between zero and eight, the actual buffer size is set to eight bytes.

useAsync

Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be opened synchronously depending on the platform. When opened asynchronously, the FileStream.BeginRead and FileStream.BeginWrite methods perform better on large reads or writes, but they might be much slower for small reads or writes. If the application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.

Exceptions
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.
Remarks
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

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;}
Exceptions
Exception Type Condition
SecurityException The caller does not have the required permission.
Remarks
This property is an operating system handle for use with operating-system-provided system calls (such as ReadFile on Windows). It will not work with C library functions that expect a file descriptor, such as fread.

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;}
Exceptions
Exception Type Condition
NotSupportedException FileStream.CanSeek for this stream is false.
IOException An I/O error occurs, such as the file being closed.
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


Property: Name (read-only)
Summary
Gets the name of the FileStream that was passed to the constructor.
C# Syntax:
public string Name {get;}
.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;}
Exceptions
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.
Remarks
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.

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:
public override IAsyncResult BeginRead(
   byte[] array,
   int offset,
   int numBytes,
   AsyncCallback userCallback,
   object stateObject
);
Parameters:

array

The buffer to read data into.

offset

The byte offset in array at which to begin reading.

numBytes

The maximum number of bytes to read.

userCallback

The method to be called when the asynchronous read operation is completed.

stateObject

A user-provided object that distinguishes this particular asynchronous read request from other requests.

Return Value:
An IAsyncResult that references the asynchronous read.
Exceptions
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.
Remarks
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.

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:
public override IAsyncResult BeginWrite(
   byte[] array,
   int offset,
   int numBytes,
   AsyncCallback userCallback,
   object stateObject
);
Parameters:

array

The buffer to write data to.

offset

The zero based byte offset in array at which to begin writing.

numBytes

The maximum number of bytes to write.

userCallback

The method to be called when the asynchronous write operation is completed.

stateObject

A user-provided object that distinguishes this particular asynchronous write request from other requests.

Return Value:
An IAsyncResult that references the asynchronous write.
Exceptions
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.
Remarks
This method overrides Stream.BeginWrite.

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();
Exceptions
Exception Type Condition
IOException An error occurred while trying to close the stream.
Remarks
This method overrides Stream.Close.

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

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Method: CreateWaitHandle()
Inherited
See base class member description: System.IO.Stream.CreateWaitHandle

Summary
Allocates a WaitHandle object.
C# Syntax:
protected virtual WaitHandle CreateWaitHandle();
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
);
Parameters:

disposing

true to release both managed and unmanaged resources; false to release only unmanaged resources.

Remarks
When the disposing parameter is true, this method releases all resources held by any managed objects that this FileStream references. This method invokes the Dispose() method of each referenced object.

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:
public override int EndRead(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

The reference to the pending asynchronous request to wait for.

Return Value:
The number of bytes read from the stream, between 0 and the number of bytes you requested. Streams only return 0 at the end of the stream, otherwise, they should block until at least 1 byte is available.
Exceptions
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.
Remarks
This method overrides Stream.EndRead.

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:
public override void EndWrite(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

The pending asynchronous I/O request.

Exceptions
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.
Remarks
This method overrides Stream.EndWrite.

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:
public virtual bool Equals(
   object obj
);

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:
~FileStream();
Exceptions
Exception Type Condition
IOException The handle for the file is invalid.
Remarks
The garbage collector calls Finalize when the current object is ready to be finalized.Finalize closes the FileStream.

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();
Exceptions
Exception Type Condition
IOException An I/O error occurs.
ObjectDisposedException The stream is closed.
Remarks
This method overrides Stream.Flush.

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:

  1. Any data previously written to the buffer is copied to the file and the buffer is cleared except for its encoder state.
  2. 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()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See 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()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See 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
);
Parameters:

position

The beginning of the range to lock.

length

The range to be locked.

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

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# 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
);
Parameters:

array

When this method returns, contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.

offset

The byte offset in array at which to begin writing.

count

The maximum number of bytes to read.

Return Value:
The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.
Exceptions
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.
Remarks
This method overrides Stream.Read.

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.
Exceptions
Exception Type Condition
NotSupportedException The current stream does not support reading.
ObjectDisposedException The current stream is closed.
Remarks
This method overrides Stream.ReadByte.

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:
public override long Seek(long offset, Seek(
   long offset,
   SeekOrigin origin
);
Parameters:

offset

The point relative to origin from which to begin seeking.

origin

Specifies the beginning, the end, or the current position as a reference point for origin, using a value of type SeekOrigin.

Return Value:
The new position in the stream.
Exceptions
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.
Remarks
This method overrides Stream.Seek.

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

value

The new length of the stream.

Exceptions
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.
Remarks
This method overrides Stream.SetLength.

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()
Inherited
See base class member description: System.Object.ToString
C# 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
);
Parameters:

position

The beginning of the range to unlock.

length

The range to be unlocked.

Exceptions
Exception Type Condition
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
);
Parameters:

array

The array to read.

offset

The byte offset in array at which to begin reading.

count

The maximum number of bytes to write.

Exceptions
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.
Remarks
This method overrides Stream.Write.

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

value

A byte to write to the stream.

Exceptions
Exception Type Condition
IOException The stream is closed.
NotSupportedException The stream does not support writing, or the stream is already closed.
Remarks
This method overrides Stream.WriteByte.

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.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.