FileStream Class

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

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
public class FileStream : Stream

The FileStream type exposes the following members.

  NameDescription
Public methodFileStream(IntPtr, FileAccess) Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public methodFileStream(SafeFileHandle, FileAccess)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode)Initializes a new instance of the FileStream class with the specified path and creation mode.
Public methodFileStream(IntPtr, FileAccess, Boolean) Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.
Public methodFileStream(SafeFileHandle, FileAccess, Int32)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess)Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.
Public methodFileStream(IntPtr, FileAccess, Boolean, Int32) Obsolete. 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.
Public methodFileStream(SafeFileHandle, FileAccess, Int32, Boolean)Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess, FileShare)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.
Public methodFileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) Obsolete. 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.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess, FileShare, Int32)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.
Public methodSupported by the XNA FrameworkFileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)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 methodFileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.
Public methodFileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.
Public methodFileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.
Top

  NameDescription
Public propertySupported by the XNA FrameworkCanReadGets a value indicating whether the current stream supports reading. (Overrides Stream.CanRead.)
Public propertySupported by the XNA FrameworkCanSeekGets a value indicating whether the current stream supports seeking. (Overrides Stream.CanSeek.)
Public propertySupported by the XNA FrameworkCanTimeoutGets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public propertySupported by the XNA FrameworkCanWriteGets a value indicating whether the current stream supports writing. (Overrides Stream.CanWrite.)
Public propertyHandle Obsolete. Gets the operating system file handle for the file that the current FileStream object encapsulates.
Public propertySupported by the XNA FrameworkIsAsyncGets a value indicating whether the FileStream was opened asynchronously or synchronously.
Public propertySupported by the XNA FrameworkLengthGets the length in bytes of the stream. (Overrides Stream.Length.)
Public propertySupported by the XNA FrameworkNameGets the name of the FileStream that was passed to the constructor.
Public propertySupported by the XNA FrameworkPositionGets or sets the current position of this stream. (Overrides Stream.Position.)
Public propertySupported by the XNA FrameworkReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public propertySafeFileHandleGets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.
Public propertySupported by the XNA FrameworkWriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top

  NameDescription
Public methodSupported by the XNA FrameworkBeginReadBegins an asynchronous read. (Overrides Stream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).)

In XNA Framework 3.0, this member is inherited from Stream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).
Public methodSupported by the XNA FrameworkBeginWriteBegins an asynchronous write. (Overrides Stream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).)

In XNA Framework 3.0, this member is inherited from Stream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).
Public methodSupported by the XNA FrameworkCloseCloses the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.)
Public methodCopyTo(Stream)Reads the bytes from the current stream and writes them to the destination stream. (Inherited from Stream.)
Public methodCopyTo(Stream, Int32)Reads all the bytes from the current stream and writes them to a destination stream, using a specified buffer size. (Inherited from Stream.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected methodSupported by the XNA FrameworkCreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public methodSupported by the XNA FrameworkDispose()Releases all resources used by the Stream. (Inherited from Stream.)
Protected methodSupported by the XNA FrameworkDispose(Boolean)Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).)
Public methodSupported by the XNA FrameworkEndReadWaits for the pending asynchronous read to complete. (Overrides Stream.EndRead(IAsyncResult).)

In XNA Framework 3.0, this member is inherited from Stream.EndRead(IAsyncResult).
Public methodSupported by the XNA FrameworkEndWriteEnds an asynchronous write, blocking until the I/O operation has completed. (Overrides Stream.EndWrite(IAsyncResult).)

In XNA Framework 3.0, this member is inherited from Stream.EndWrite(IAsyncResult).
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeEnsures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. (Overrides Object.Finalize().)
Public methodSupported by the XNA FrameworkFlush()Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)
Public methodFlush(Boolean)Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.
Public methodGetAccessControlGets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.
Public methodSupported by the XNA FrameworkGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodLockPrevents other processes from reading from or writing to the FileStream.
Protected methodSupported by the XNA FrameworkMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodObjectInvariantInfrastructure. Provides support for a Contract. (Inherited from Stream.)
Public methodSupported by the XNA FrameworkReadReads a block of bytes from the stream and writes the data in a given buffer. (Overrides Stream.Read(Byte[], Int32, Int32).)
Public methodSupported by the XNA FrameworkReadByteReads a byte from the file and advances the read position one byte. (Overrides Stream.ReadByte().)
Public methodSupported by the XNA FrameworkSeekSets the current position of this stream to the given value. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public methodSetAccessControlApplies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.
Public methodSupported by the XNA FrameworkSetLengthSets the length of this stream to the given value. (Overrides Stream.SetLength(Int64).)
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodUnlockAllows access by other processes to all or part of a file that was previously locked.
Public methodSupported by the XNA FrameworkWriteWrites a block of bytes to this stream using data from a buffer. (Overrides Stream.Write(Byte[], Int32, Int32).)
Public methodSupported by the XNA FrameworkWriteByteWrites a byte to the current position in the file stream. (Overrides Stream.WriteByte(Byte).)
Top

Use the FileStream class to read from, write to, open, and close files on a file system, as well as to manipulate other file-related operating system handles including pipes, standard input, and standard output. You can specify read and write operations to be either synchronous or asynchronous. FileStream buffers input and output for better performance.

FileStream objects support random access to files using the Seek method. Seek 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.

NoteNote

Disk files always support random access. At the time of construction, the CanSeek property value 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 value is true. Otherwise, the CanSeek property value is false.

Although the synchronous methods Read and Write and the asynchronous methods BeginRead, BeginWrite, EndRead, and EndWrite can work in either synchronous or asynchronous mode, the mode affects the performance of these methods. FileStream defaults to opening files synchronously, but provides the FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) constructor to open files asynchronously.

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

For directory and other file 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.

For a list of common I/O tasks, see Common I/O Tasks.

Detection of stream position changes

When a 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 FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to assure that the operating system's handle position is the same as the cached position used by the FileStream object.

If an unexpected change in the handle position is detected in a call to the Read 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 Write method, the contents of the buffer are discarded and an IOException is thrown.

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

The following example demonstrates some of the FileStream constructors.


using System;
using System.IO;
using System.Text;

class Test
{

    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        //Create the file.
        using (FileStream fs = File.Create(path))
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++)
            {
                AddText(fs, Convert.ToChar(i).ToString());

            }
        }

        //Open the stream and read it back.
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }

    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}


The following example opens a file or creates it if it does not already exist, and appends information to the end of the file.


using System;
using System.IO;
using System.Text;

class FSOpenWrite
{
    public static void Main()
    {
        FileStream fs=new FileStream("c:\\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
        fs.Close();
        StreamWriter sw=new StreamWriter("c:\\Variables.txt", true, Encoding.ASCII);
        string NextLine="This is the appended line.";
        sw.Write(NextLine);
        sw.Close();
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft