System.IO.FileStream Class

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

See Also: FileStream Members

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
public class FileStream : Stream

Remarks

Use the System.IO.FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the FileStream.Read(Byte[], int, int), FileStream.Write(Byte[], int, int), Stream.CopyTo(Stream), and FileStream.Flush methods to perform synchronous operations, or the FileStream.ReadAsync(Byte[], int, int, System.Threading.CancellationToken), FileStream.WriteAsync(Byte[], int, int, System.Threading.CancellationToken), Stream.CopyToAsync(Stream), and FileStream.FlushAsync(System.Threading.CancellationToken) methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a win8_appname_long app or desktop_appname app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. System.IO.FileStream buffers input and output for better performance.

The FileStream.IsAsync property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the System.IO.FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the FileStream.IsAsync property does not have to be true to call the FileStream.ReadAsync(Byte[], int, int, System.Threading.CancellationToken), FileStream.WriteAsync(Byte[], int, int, System.Threading.CancellationToken), or Stream.CopyToAsync(Stream) method. When the FileStream.IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.

The FileStream.Seek(long, SeekOrigin) method supports random access to files. FileStream.Seek(long, SeekOrigin) 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 members of the System.IO.SeekOrigin enumeration.

Note:

Disk files always support random access. At the time of construction, the FileStream.CanSeek property value is set to true or false depending on the underlying file type.If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the FileStream.CanSeek property value is true. Otherwise, the FileStream.CanSeek property value is false.

If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

For directory operations and other file operations, see the System.IO.File, System.IO.Directory, and System.IO.Path classes. The System.IO.File class is a utility class that has static methods primarily for the creation of System.IO.FileStream objects based on file paths. The System.IO.MemoryStream class creates a stream from a byte array and is similar to the System.IO.FileStream class.

For a list of common file and directory operations, see Common I/O Tasks.

Detection of Stream Position Changes

When a System.IO.FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the System.IO.FileStream object and the cached data in the buffer could be compromised. The System.IO.FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the System.IO.FileStream object.

If an unexpected change in the handle position is detected in a call to the FileStream.Read(Byte[], int, int) method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

If an unexpected change in the handle position is detected in a call to the FileStream.Write(Byte[], int, int) method, the contents of the buffer are discarded and an System.IO.IOException exception is thrown.

A System.IO.FileStream object will not have an exclusive hold on its handle when either the FileStream.SafeFileHandle property is accessed to expose the handle or the System.IO.FileStream object is given the FileStream.SafeFileHandle property in its constructor.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Example

The following example demonstrates the use of a System.IO.FileStream object.

C# Example

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

Requirements

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0