Export (0) Print
Expand All

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
/** @attribute ComVisibleAttribute(true) */ 
public class FileStream extends Stream
ComVisibleAttribute(true) 
public class FileStream extends Stream
Not applicable.

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.

Be sure to call the Dispose method on all FileStream objects, especially in environments with limited disk space. Performing IO operations can raise an exception if there is no disk space available and the Dispose method is not called before the FileStream is finalized.

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

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

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

import System.*;
import System.IO.*;
import System.Text.*;

class Test
{
    public static void main(String[] args)
    {
        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, System.Convert.ToString((char)i));

                    //Split the output at every 10th character.
                    if (Math.IEEEremainder(Convert.ToDouble(i), 10) == 0) {
                        AddText(fs, "\r\n");
                    }
                }
            }
            finally {
                fs.Dispose();
            }
        }
        //Open the stream and read it back.
        {
            FileStream fs = File.OpenRead(path);
            try {
                ubyte b[] = new ubyte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);
                while (fs.Read(b, 0, b.length) > 0) {
                    Console.WriteLine(temp.GetString(b));
                }
            }
            finally {
                fs.Dispose();
            }
        }
    } //main

    private static void AddText(FileStream fs, String value)
    {
        ubyte info[] = (new UTF8Encoding(true)).GetBytes(value);
        fs.Write(info, 0, info.length);
    } //AddText
} //Test

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

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

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft