FileStream Class (System.IO)

Switch View :
ScriptFree
.NET Framework Class Library
FileStream Class

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

Inheritance Hierarchy

System.Object
  System.MarshalByRefObject
    System.IO.Stream
      System.IO.FileStream
        System.IO.IsolatedStorage.IsolatedStorageFileStream

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

Visual Basic
<ComVisibleAttribute(True)> _
Public Class FileStream _
	Inherits Stream
C#
[ComVisibleAttribute(true)]
public class FileStream : Stream
Visual C++
[ComVisibleAttribute(true)]
public ref class FileStream : public Stream
F#
[<ComVisibleAttribute(true)>]
type FileStream =  
    class
        inherit Stream
    end

The FileStream type exposes the following members.

Constructors

  Name Description
Public method FileStream(IntPtr, FileAccess) Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public method FileStream(SafeFileHandle, FileAccess) Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.
Public method Supported by the XNA Framework FileStream(String, FileMode) Initializes a new instance of the FileStream class with the specified path and creation mode.
Public method FileStream(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 method FileStream(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 method Supported by the XNA Framework FileStream(String, FileMode, FileAccess) Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.
Public method FileStream(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 method FileStream(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 method Supported by the XNA Framework FileStream(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 method FileStream(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 method Supported by the XNA Framework FileStream(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 method Supported by the XNA Framework FileStream(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 method FileStream(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 method FileStream(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 method FileStream(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
Properties

  Name Description
Public property Supported by the XNA Framework CanRead Gets a value indicating whether the current stream supports reading. (Overrides Stream.CanRead.)
Public property Supported by the XNA Framework CanSeek Gets a value indicating whether the current stream supports seeking. (Overrides Stream.CanSeek.)
Public property Supported by the XNA Framework CanTimeout Gets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public property Supported by the XNA Framework CanWrite Gets a value indicating whether the current stream supports writing. (Overrides Stream.CanWrite.)
Public property Handle Obsolete. Gets the operating system file handle for the file that the current FileStream object encapsulates.
Public property Supported by the XNA Framework IsAsync Gets a value indicating whether the FileStream was opened asynchronously or synchronously.
Public property Supported by the XNA Framework Length Gets the length in bytes of the stream. (Overrides Stream.Length.)
Public property Supported by the XNA Framework Name Gets the name of the FileStream that was passed to the constructor.
Public property Supported by the XNA Framework Position Gets or sets the current position of this stream. (Overrides Stream.Position.)
Public property Supported by the XNA Framework ReadTimeout Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public property SafeFileHandle Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.
Public property Supported by the XNA Framework WriteTimeout Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top
Methods

  Name Description
Public method Supported by the XNA Framework BeginRead Begins 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 method Supported by the XNA Framework BeginWrite Begins 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 method Supported by the XNA Framework Close Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.)
Public method CopyTo(Stream) Reads the bytes from the current stream and writes them to the destination stream. (Inherited from Stream.)
Public method CopyTo(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 method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework CreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public method Supported by the XNA Framework Dispose() Releases all resources used by the Stream. (Inherited from Stream.)
Protected method Supported by the XNA Framework Dispose(Boolean) Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).)
Public method Supported by the XNA Framework EndRead Waits 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 method Supported by the XNA Framework EndWrite Ends 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 method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. (Overrides Object.Finalize().)
Public method Supported by the XNA Framework Flush() Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)
Public method Flush(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 method GetAccessControl Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Lock Prevents other processes from reading from or writing to the FileStream.
Protected method Supported by the XNA Framework MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method ObjectInvariant Infrastructure. Provides support for a Contract. (Inherited from Stream.)
Public method Supported by the XNA Framework Read Reads a block of bytes from the stream and writes the data in a given buffer. (Overrides Stream.Read(Byte[], Int32, Int32).)
Public method Supported by the XNA Framework ReadByte Reads a byte from the file and advances the read position one byte. (Overrides Stream.ReadByte().)
Public method Supported by the XNA Framework Seek Sets the current position of this stream to the given value. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public method SetAccessControl Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.
Public method Supported by the XNA Framework SetLength Sets the length of this stream to the given value. (Overrides Stream.SetLength(Int64).)
Public method Supported by the XNA Framework ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Unlock Allows access by other processes to all or part of a file that was previously locked.
Public method Supported by the XNA Framework Write Writes a block of bytes to this stream using data from a buffer. (Overrides Stream.Write(Byte[], Int32, Int32).)
Public method Supported by the XNA Framework WriteByte Writes a byte to the current position in the file stream. (Overrides Stream.WriteByte(Byte).)
Top
Remarks

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.

Note Note

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.

Examples

The following example demonstrates some of the FileStream constructors.

Visual Basic

Imports System
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        ' Delete the file if it exists.
        If File.Exists(path) Then
            File.Delete(path)
        End If

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:" & Environment.NewLine)

        Dim i As Integer

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) As Byte
        Dim temp As UTF8Encoding = New UTF8Encoding(True)

        Do While fs.Read(b, 0, b.Length) > 0
            Console.WriteLine(temp.GetString(b))
        Loop

        fs.Close()
    End Sub

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
End Class


C#

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);
    }
}


Visual C++

using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
   array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
   fs->Write( info, 0, info->Length );
}

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";

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

   //Create the file.
   {
      FileStream^ fs = File::Create( path );
      try
      {
         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() );

            //Split the output at every 10th character.
            if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
            {
               AddText( fs, "\r\n" );
            }
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }

   //Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      try
      {
         array<Byte>^b = gcnew array<Byte>(1024);
         UTF8Encoding^ temp = gcnew UTF8Encoding( true );
         while ( fs->Read( b, 0, b->Length ) > 0 )
         {
            Console::WriteLine( temp->GetString( b ) );
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
}


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

Visual Basic

Imports System
Imports System.IO
Imports System.Text

Class FSOpenWrite

    Public Shared Sub Main()
        Dim fs As New FileStream("c:\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write)
        fs.Close()
        Dim sw As New StreamWriter("c:\Variables.txt", True, Encoding.ASCII)
        Dim NextLine As String = "This is the appended text."
        sw.Write(NextLine)
        sw.Close()
    End Sub 'Main
End Class 'FSOpenWrite


C#

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();
    }
}


Visual C++

using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   FileStream^ fs = gcnew FileStream( "c:\\Variables.txt",FileMode::Append,FileAccess::Write,FileShare::Write );
   fs->Close();
   StreamWriter^ sw = gcnew StreamWriter( "c:\\Variables.txt",true,Encoding::ASCII );
   String^ NextLine = "This is the appended line.";
   sw->Write( NextLine );
   sw->Close();
}



Version Information

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

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.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Community Content

Eric Hui Zhang
test
test

default_name
Problems in using system namespace
#include<iostream>

using namespace std;
using namespace System;
using namespace System::IO;

int main()
{
cout<<"something";
return 0;
}

When I execute this in vc++ 6.0, it gives me the following errors:
D:\programs\client\filetransfer.cpp(4) : error C2653: 'System' : is not a class or namespace name
D:\programs\client\filetransfer.cpp(5) : error C2871: 'IO' : does not exist or is not a namespace
D:\programs\client\filetransfer.cpp(5) : error C2871: 'System' : does not exist or is not a namespace
Error executing cl.exe.

I've tried to provide extra path for required dll's like mscorlib.dll present in c:\windows\mircrosoft .net\    
folder and also I've used system.dll. Actually I am trying to transfer files(any kind) accross the network through sockets.
So I tried this simple code to check the system namespace, but not working!!
Any suggestions?