System.IO.FileStream Class

public class FileStream : Stream

Base Types

Object
  MarshalByRefObject
    Stream
      FileStream

This type implements IDisposable.

Assembly

mscorlib

Library

BCL

Summary

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

Description

FileStream is used for reading and writing files on a file system, as well as other file-related operating system handles such as pipes, standard input, standard output. FileStream buffers input and output for better performance.

The FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods (System.IO.FileStream.Read(System.Byte[],System.Int32,System.Int32) and System.IO.FileStream.Write(System.Byte[],System.Int32,System.Int32)) and the asynchronous methods (System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) and System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) ). Both sets of methods will work in either mode; however, the mode will affect the performance of these methods. FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously.

When accessing files, a security check is performed when the file is created or opened. The security check is typically not done again unless the file is closed and reopened. [Note: Checking permissions when the file is first accessed minimizes the impact of the security check on application performance (since opening a file happens once, while reading and writing can happen multiple times).]

Note that if an opened file is passed to an untrusted caller, the security system can, but is not required to prevent the caller from accessing the file.

FileStream objects support random access to files using the System.IO.FileStream.Seek(System.Int64,System.IO.SeekOrigin) method, and the System.IO.Stream.CanSeek properties of FileStream instances encapsulating files are set to true . The System.IO.FileStream.Seek(System.Int64,System.IO.SeekOrigin) method allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three values of the SeekOrigin enumeration.

If a FileStream encapsulates a device that does not support seeking, its System.IO.FileStream.CanSeek property is false . [Note: For additional information, see System.IO.Stream.CanSeek.]

[Note: The File class provides methods for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and functions similarly to a FileStream.]

Example

The following example demonstrates the use of a FileStream object.

using System;
using System.IO;

class Directory {
   public static void Main(String[] args) { 
      FileStream fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);
      StreamWriter w = new StreamWriter(fs);         
      w.BaseStream.Seek(0, SeekOrigin.End);   // Set the file pointer to the end.

      Log ("Test1", w);
      Log ("Test2", w);
 
      w.Close(); // Close the writer and underlying file.     

      fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Read);

      StreamReader r = new StreamReader(fs);        
      r.BaseStream.Seek(0, SeekOrigin.Begin);   
      DumpLog (r);
   }

   public static void Log (String logMessage, StreamWriter w) {
      w.Write("Log Entry : ");
      w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
      w.WriteLine(":");
      w.WriteLine(":{0}", logMessage);
      w.WriteLine ("-------------------------------");
      w.Flush();  
   }

   public static void DumpLog (StreamReader r) {
      while (r.Peek() > -1) { // While not at the end of the file, write to standard output.     
        Console.WriteLine(r.ReadLine());
      }

      r.Close();
   }
}
Some example output is

Log Entry : 9:26:21 AM Friday, July 06, 2001

:

:Test1

-------------------------------

Log Entry : 9:26:21 AM Friday, July 06, 2001

:

:Test2

-------------------------------

See Also

System.IO Namespace

Members

FileStream Constructors

FileStream(System.String, System.IO.FileMode) Constructor
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess) Constructor
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) Constructor
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, int) Constructor
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, int, bool) Constructor

FileStream Methods

FileStream.BeginRead Method
FileStream.BeginWrite Method
FileStream.Close Method
FileStream.Dispose Method
FileStream.EndRead Method
FileStream.EndWrite Method
FileStream.Finalize Method
FileStream.Flush Method
FileStream.Read Method
FileStream.ReadByte Method
FileStream.Seek Method
FileStream.SetLength Method
FileStream.Write Method
FileStream.WriteByte Method

FileStream Properties

FileStream.CanRead Property
FileStream.CanSeek Property
FileStream.CanWrite Property
FileStream.IsAsync Property
FileStream.Length Property
FileStream.Position Property


FileStream(System.String, System.IO.FileMode) Constructor

public FileStream(string path, FileMode mode);

Summary

Constructs and initializes a new instance of the FileStream class with the specified path and creation mode.

Parameters

path
A String containing the relative or absolute path for the file that the current FileStream object will encapsulate.
mode
A FileMode value that determines how to open or create the file.

Exceptions

Exception TypeCondition
ArgumentExceptionpath is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
ArgumentNullExceptionpath is null .
SecurityExceptionThe caller does not have the required permission.
FileNotFoundExceptionmode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.

IOExceptionAn I/O error occurred, such as specifying System.IO.FileMode.CreateNew when the file specified by path already exists.
DirectoryNotFoundExceptionThe directory information specified in path does not exist.
PathTooLongExceptionThe length of path or the absolute path information for path exceeds the system-defined maximum length.
ArgumentOutOfRangeExceptionmode contains an invalid value.

Description

This constructor sets System.IO.FileAccess.ReadWrite access to the file, and the System.IO.Stream.CanRead and System.IO.Stream.CanWrite properties of the current instance are set to true .

[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.]

System.IO.Stream.CanSeek is true for all FileStream objects that encapsulate files. If path specifies a device that does not support seeking, the System.IO.FileStream.CanSeek property of the resulting FileStream is required to be false . [Note: For additional information, see System.IO.Stream.CanSeek . ]

Requests to open the file for writing by the current or another thread will fail until the FileStream object has been closed. Read attempts will succeed.

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream(System.String, System.IO.FileMode, System.IO.FileAccess) Constructor

public FileStream(string path, FileMode mode, FileAccess access);

Summary

Constructs and initializes a new instance of the FileStream class with the specified path, creation mode, and access type.

Parameters

path
A String containing the relative or absolute path for the file that the current FileStream object will encapsulate.
mode
A FileMode value that determines how to open or create the file.
access
A FileAccess value that determines how the file may be accessed by the FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties.

Exceptions

Exception TypeCondition
ArgumentNullExceptionpath is null .
ArgumentExceptionpath is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
FileNotFoundExceptionmode is System.IO.FileMode.Truncate or System.IO.FileMode.Open , but the specified file was not found. If a different mode is specified and the file was not found, a new one is created.

IOExceptionAn I/O error occurred, such as specifying System.IO.FileMode.CreateNew when the file specified by path already exists.
SecurityExceptionThe caller does not have the required permission.
DirectoryNotFoundExceptionThe directory information specified by path does not exist.
UnauthorizedAccessExceptionThe access requested is not permitted by the operating system for the specified path.
PathTooLongExceptionThe length of path or the absolute path information for path exceeds the system-defined maximum length.
ArgumentOutOfRangeExceptionmode or access contain an invalid value.

Description

This constructor sets read/write access to the file. Requests to open the file for writing by the current or another thread will fail until the FileStream object has been closed. Read attempts will succeed.

[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.]

System.IO.Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting FileStream is required to be false . For additional information, see System.IO.Stream.CanSeek .

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) Constructor

public FileStream(string path, FileMode mode, FileAccess access, FileShare share);

Summary

Constructs and initializes a new instance of the FileStream class with the specified path, creation mode, access type, and sharing permission.

Parameters

path
A String containing relative or absolute path for the file that the current FileStream object will encapsulate.
mode
A FileMode value that determines how to open or create the file.
access
A FileAccess value that determines how the file may be accessed by the FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties. For additional information, see System.IO.Stream.CanRead and System.IO.Stream.CanWrite.
share
A FileShare value that determines how the file will be shared by processes.

Exceptions

Exception TypeCondition
ArgumentNullExceptionpath is null .
ArgumentExceptionpath is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
FileNotFoundExceptionmode is System.IO.FileMode.Truncate or System.IO.FileMode.Open , but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.

IOExceptionAn I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
SecurityExceptionThe caller does not have the required permission.
DirectoryNotFoundExceptionThe directory information specified by path does not exist.
UnauthorizedAccessExceptionThe access requested is not permitted by the operating system for the specified path.
PathTooLongExceptionThe length of path or the absolute path information for path exceeds the system-defined maximum length.
ArgumentOutOfRangeExceptionmode, access, or share contains an invalid value.

Description

This constructor sets read/write access to the file. Requests to open the file for writing by the current or another process will fail until the FileStream object has been closed. Read attempts will succeed.

[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.]

System.IO.Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting FileStream is required to be false . For additional information, see System.IO.Stream.CanSeek .

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, int) Constructor

public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize);

Summary

Constructs and initializes a new instance of the FileStream class.

Parameters

path
A String containing the 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 value that determines how the file may be accessed by the FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties. For additional information, see System.IO.Stream.CanRead and System.IO.Stream.CanWrite .
share
A FileShare constant that determines how the file will be shared by processes.
bufferSize
A Int32 containing the desired buffer size in bytes.

Exceptions

Exception TypeCondition
ArgumentNullExceptionThe path parameter is null .
ArgumentExceptionpath is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
ArgumentOutOfRangeExceptionbufferSize is less than or equal to zero.

-or-

mode, access, or share contain an invalid value.

FileNotFoundExceptionmode is System.IO.FileMode.Truncate or System.IO.FileMode.Open , but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.

IOExceptionAn I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
SecurityExceptionThe caller does not have the required permission.
DirectoryNotFoundExceptionThe directory information specified in path does not exist.
UnauthorizedAccessExceptionThe access requested is not permitted by the operating system for the specified path.
PathTooLongExceptionThe length of path or the absolute path information for path exceeds the system-defined maximum length.

Description

[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.]

System.IO.Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting FileStream is required to be false . For additional information, see System.IO.Stream.CanSeek .

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, int, bool) Constructor

public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync);

Summary

Constructs and initializes a new instance of the FileStream class.

Parameters

path
A String containing the relative or absolute path for the file that the new FileStream object will encapsulate.
mode
A FileMode value that determines how to open or create the file.
access
A FileAccess value that determines how the file may be accessed by the FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties.
share
A FileShare value that determines how the file will be shared by processes.
bufferSize
A Int32 containing the desired buffer size in bytes.
useAsync
A Boolean value that specifies whether to use asynchronous I/O or synchronous I/O. If the underlying operating system does not support asynchronous I/O, the FileStream ignores this parameter and uses synchronous I/O.

Exceptions

Exception TypeCondition
ArgumentNullExceptionpath is null .
ArgumentExceptionpath is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
ArgumentOutOfRangeExceptionbufferSize is less than or equal to zero.

-or-

mode, access, or share contain an invalid value.

FileNotFoundExceptionmode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.

IOExceptionAn I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
SecurityExceptionThe caller does not have the required permission.
DirectoryNotFoundExceptionThe directory information specified by path does not exist.
UnauthorizedAccessExceptionThe access requested is not permitted by the operating system for the specified path.
PathTooLongExceptionThe length of path or the absolute path information for path exceeds the system-defined maximum length.

Description

This constructor sets read/write access to the file. Requests to open the file for writing by this or another process will fail until the FileStream object has been closed. Read attempts will succeed.

[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.]

System.IO.Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting FileStream is required to be false . For additional information, see System.IO.Stream.CanSeek .

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.BeginRead Method

public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject);

Summary

Begins an asynchronous read.

Parameters

array
A Byte array that specifies the buffer to read data into.
offset
A Int32 containing the zero based byte offset in array at which to begin reading.
numBytes
A Int32 containing the maximum number of bytes to read.
userCallback
A AsyncCallback delegate that references the method to be called when the asynchronous read operation is completed.
stateObject
An application defined object containing the status of the asynchronous read.

Return Value

A IAsyncResult that references the asynchronous read.

Exceptions

Exception TypeCondition
ArgumentExceptionThe sum of offset andnumBytes is greater than the length of array.
ArgumentNullExceptionarray is null .
ArgumentOutOfRangeExceptionoffset or numBytes is negative.
IOExceptionThe asynchronous read operation attempted to read past the end of the file.

Description

To determine the number of bytes read, call System.IO.Stream.EndRead(System.IAsyncResult) with the returned IAsyncResult.

Multiple simultaneous asynchronous requests render the request completion order uncertain.

[Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead.

This method overrides System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object).

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.BeginWrite Method

public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject);

Summary

Begins an asynchronous write operation.

Parameters

array
A Byte array buffer to write data to.
offset
A Int32 containing the zero based byte offset in array at which to begin writing.
numBytes
A Int32 containing the maximum number of bytes to write.
userCallback
A AsyncCallback delegate that references the method to be called when the asynchronous write operation is completed.
stateObject
An application defined object containing the status of the asynchronous read.

Return Value

A IAsyncResult that references the asynchronous write.

Exceptions

Exception TypeCondition
ArgumentExceptionThe sum of offset and numBytes is greater than the length of array.
ArgumentNullExceptionarray is null .
ArgumentOutOfRangeExceptionoffset or numBytes is negative.
IOExceptionThe stream does not support writing, or an I/O error occurred.

Description

Multiple simultaneous asynchronous requests render the request completion order uncertain.

[Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite.

This method overrides System.IO.Stream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object).

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Close Method

public override void Close();

Summary

Closes the file and releases any resources associated with the current file stream.

Description

This method is equivalent to System.IO.FileStream.Dispose(System.Boolean)(true ).

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 System.IO.FileStream.Flush before invoking Close . Following a call to Close , any operations on the file stream might raise exceptions. Invoking this method on the same instance multiple times does not result in an exception.

[Usage: The System.IO.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.]

[Note: This method overrides System.IO.Stream.Close. ]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Dispose Method

protected virtual void Dispose(bool disposing);

Summary

Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.

Parameters

disposing
Specify true to release both managed and unmanaged resources, or specify false to release only unmanaged resources.

Exceptions

Exception TypeCondition
IOExceptionAn I/O error occurred.

Description

When the disposing parameter is true , this method releases all resources held by any managed objects that this FileStream references.

[Note: System.IO.FileStream.Dispose(System.Boolean) may be called multiple times by other objects. When overriding System.IO.FileStream.Dispose(System.Boolean)(Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.FileStream.Dispose(System.Boolean) .

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.EndRead Method

public override int EndRead(IAsyncResult asyncResult);

Summary

Ends a pending asynchronous read request, and blocks until the read request has completed.

Parameters

asyncResult
The IAsyncResult object for the pending asynchronous request.

Return Value

A Int32 containing the number of bytes read from the stream. Returns 0 only if the end of the file has been reached, otherwise, this method blocks until at least one byte is available.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by a call to System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object).
InvalidOperationExceptionSystem.IO.FileStream.EndRead(System.IAsyncResult) was called multiple times with asyncResult .

Description

EndRead will block until the I/O operation has completed.

[Note: This method overrides System.IO.Stream.EndRead(System.IAsyncResult).]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.EndWrite Method

public override void EndWrite(IAsyncResult asyncResult);

Summary

Ends an asynchronous write, blocking until the I/O operation has completed.

Parameters

asyncResult
The IAsyncResult object for the pending asynchronous request.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by a call to System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object).
InvalidOperationExceptionSystem.IO.FileStream.EndWrite(System.IAsyncResult) was called multiple times with asyncResult .

Description

System.IO.FileStream.EndWrite(System.IAsyncResult) will block until the I/O operation has completed.

[Note: This method overrides System.IO.Stream.EndWrite(System.IAsyncResult).]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Finalize Method

~FileStream();

Summary

Releases the resources held by the current instance.

Description

System.IO.FileStream.Finalize closes the FileStream.

[Note: Application code does not call this method; it is automatically invoked by during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize(System.Object), and System.Object.Finalize.

This method overrides System.Object.Finalize.

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Flush Method

public override void Flush();

Summary

Updates the underlying file with the current state of the buffer and subsequently clears the buffer.

Exceptions

Exception TypeCondition
IOExceptionAn I/O error occurred.
ObjectDisposedExceptionThe current instance has already been closed.

Description

A FileStream buffer can be used either for reading or writing. If data was copied to the buffer for writing, it is written to the file and the buffer is cleared.

If data was copied to the buffer for reading, and the System.IO.Stream.CanSeek property is true , the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared.

[Note: This method overrides System.IO.Stream.Flush.]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Read Method

public override int Read(byte[] array, int offset, int count);

Summary

Reads a block of bytes from the stream and returns the data in the specified buffer.

Parameters

array
A Byte array. When this method returns, the bytes between offset and (offset + count - 1) in array are replaced by the bytes read from the current stream.
offset
A Int32 containing the byte offset in array at which to begin writing data read from the current stream.
count
A Int32 containing maximum number of bytes to read.

Return Value

A Int32 containing the total number of bytes read into the buffer, or zero if the end of the stream is reached.

Exceptions

Exception TypeCondition
ArgumentNullExceptionarray is null .
ArgumentOutOfRangeExceptionoffset or count is negative.
NotSupportedExceptionThe current stream does not support reading.
IOExceptionAn I/O error occurred.
ArgumentExceptionoffset + count is greater than the length of array.
ObjectDisposedExceptionThe current stream is closed.

Description

The System.IO.FileStream.Read(System.Byte[],System.Int32,System.Int32) method returns zero only after reaching the end of the stream. Otherwise, System.IO.FileStream.Read(System.Byte[],System.Int32,System.Int32) always reads at least one byte from the stream before returning. If no data is available from the stream, this method blocks until at least one byte of data can be returned.

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.

[Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead.]

[Note: This method overrides System.IO.Stream.Read(System.Byte[],System.Int32,System.Int32) .]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.ReadByte Method

public override int ReadByte();

Summary

Reads a byte from the file and advances the read position one byte.

Return Value

The byte cast to a Int32, or -1 if the end of the stream has been reached.

Exceptions

Exception TypeCondition
ObjectDisposedExceptionThe current stream is closed.
NotSupportedExceptionThe current stream does not support reading.

Description

[Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead.

This method overrides System.IO.Stream.ReadByte.

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Seek Method

public override long Seek(long offset, SeekOrigin origin);

Summary

Sets the current position of the current stream to the specified value.

Parameters

offset
A Int64 containing the position relative to origin from which to begin seeking.
origin
A SeekOrigin value specifying the beginning, the end, or the current position as a reference point for offset.

Return Value

A Int64 containing the new position in the stream.

Exceptions

Exception TypeCondition
IOExceptionAn I/O error occurred.
NotSupportedExceptionThe stream does not support seeking.
ArgumentExceptionAttempted seeking before the beginning of the stream or to more than one byte past the end of the stream.
ObjectDisposedExceptionThe current stream is closed.

Description

[Note: Use the System.IO.FileStream.CanSeek property to determine whether the current instance supports seeking. For additional information, see System.IO.Stream.CanSeek .]

[Usage: 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.]

[Note: This method overrides System.IO.Stream.Seek(System.Int64,System.IO.SeekOrigin).]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.SetLength Method

public override void SetLength(long value);

Summary

Sets the length of the current stream to the specified value.

Parameters

value
A Int64 that specifies the new length of the stream.

Exceptions

Exception TypeCondition
IOException An I/O error occurred.
NotSupportedExceptionThe current stream does not support writing and seeking.
ArgumentOutOfRangeExceptionvalue is less than zero.

Description

If value is less than the current length of the stream, the stream is truncated. If value is greater than the current length of the stream, the stream is expanded, and the contents of the stream between the old and the new length are undefined. A stream is required to support both writing and seeking to implement System.IO.FileStream.SetLength(System.Int64).

[Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing, and the System.IO.FileStream.CanSeek property to determine whether seeking is supported. For additional information, see System.IO.Stream.CanWrite and System.IO.Stream.CanSeek .

This method overrides System.IO.Stream.SetLength(System.Int64).

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Write Method

public override void Write(byte[] array, int offset, int count);

Summary

Writes a block of bytes from a specified byte array to the current stream.

Parameters

array
The Byte array to read.
offset
A Int32 that specifies the byte offset in array at which to begin reading.
count
A Int32 that specifies the maximum number of bytes to write to the current stream.

Exceptions

Exception TypeCondition
ArgumentNullExceptionarray is null .
ArgumentExceptionoffset + count is greater than the length of array.
ArgumentOutOfRangeExceptionoffset or count is negative.
IOExceptionAn I/O error occurred.
NotSupportedExceptionThe current stream does not support writing.

Description

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 System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite.

This method overrides System.IO.Stream.Write(System.Byte[],System.Int32,System.Int32).

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.WriteByte Method

public override void WriteByte(byte value);

Summary

Writes a byte to the current position in the file stream.

Parameters

value
A Byte to write to the stream.

Exceptions

Exception TypeCondition
IOExceptionThe current stream is closed.
NotSupportedExceptionThe current stream does not support writing.

Description

[Usage: Use System.IO.FileStream.WriteByte(System.Byte) method to write a byte to a FileStream efficiently.]

[Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite.

This method overrides System.IO.Stream.WriteByte(System.Byte).

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.CanRead Property

public override bool CanRead { get; }

Summary

Gets a Boolean value indicating whether the current stream supports reading.

Property Value

true if the stream supports reading; false if the stream is closed or was opened with write-only access.

Description

This property is read-only.

[Note: This property overrides System.IO.Stream.CanRead.

If a class derived from Stream does not support reading, the Read and Peek methods throw a NotSupportedException .

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.CanSeek Property

public override bool CanSeek { get; }

Summary

Gets a Boolean value indicating whether the current stream supports seeking.

Property Value

true if the stream supports seeking; false if the stream is closed or if the FileStream was constructed from an operating-system handle such as a pipe or output to the console.

Description

[Note: If a class derived from Stream does not support seeking, a call to System.IO.FileStream.Length (both get and set ), System.IO.FileStream.Position, or System.IO.FileStream.Seek(System.Int64,System.IO.SeekOrigin) throws a NotSupportedException .

This property overrides System.IO.Stream.CanSeek.

]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.CanWrite Property

public override bool CanWrite { get; }

Summary

Gets a Boolean value indicating whether the current stream supports writing.

Property Value

true if the stream supports writing; false if the stream is closed or was opened with read-only access.

Description

If a class derived from Stream does not support writing, a call to System.IO.FileStream.Write(System.Byte[],System.Int32,System.Int32), System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object), or System.IO.FileStream.EndWrite(System.IAsyncResult) will throw a NotSupportedException .

[Note: This property overrides System.IO.Stream.CanWrite.]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.IsAsync Property

public virtual bool IsAsync { get; }

Summary

Gets a Boolean value indicating whether the current instance was opened asynchronously or synchronously.

Property Value

true if the current FileStream was opened asynchronously; otherwise, false .

Description

[Behaviors: This property is read-only.]

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Length Property

public override long Length { get; }

Summary

Gets the length in bytes of the stream.

Property Value

A Int64 value containing the length of the stream in bytes.

Exceptions

Exception TypeCondition
NotSupportedExceptionSystem.IO.FileStream.CanSeek for this stream is false .
IOExceptionAn I/O error occurred, such as the file being closed.

Description

This property is read-only.

See Also

System.IO.FileStream Class, System.IO Namespace

FileStream.Position Property

public override long Position { get; set; }

Summary

Gets or sets the current position of this stream.

Property Value

A Int64 containing the current position of this stream.

Exceptions

Exception TypeCondition
NotSupportedExceptionThe current stream does not support seeking.
IOExceptionAn I/O error occurred.
EndOfStreamExceptionAttempted seeking past the end of a stream that does not support this.
ArgumentOutOfRangeExceptionThe value specified for a set operation is negative.

Description

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.

See Also

System.IO.FileStream Class, System.IO Namespace