Export (0) Print
Expand All

FileStream Class

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

For a list of all members of this type, see FileStream Members.

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

[Visual Basic]
Public Class FileStream
   Inherits Stream
[C#]
public class FileStream : Stream
[C++]
public __gc class FileStream : public Stream
[JScript]
public class FileStream extends Stream

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.

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 such as pipes, standard input, amd 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   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(IntPtr, FileAccess, Boolean, Int32, Boolean) and FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) constructors 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 an example of using this class, see the Example section below. The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file. File.Move

FileInfo.MoveTo

Delete a file. File.Delete

FileInfo.Delete

Copy a file. File.Copy

FileInfo.CopyTo

Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File
Retrieve a file extension. Path.GetExtension
Retrieve the fully qualified path of a file. Path.GetFullPath
Retrieve the file name and extension from a path. Path.GetFileName
Change the extension of a file. Path.ChangeExtension

Example

[Visual Basic, C#, C++] 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())

            'Split the output at every 10th character.
            If Math.IEEERemainder(Convert.ToDouble(i), 10) = 0 Then
                AddText(fs, Environment.NewLine)
            End If
        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());

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

[C++] 
#using <mscorlib.dll>

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

void AddText(FileStream* fs, String* value) {
    Byte info[] = (new UTF8Encoding(true))->GetBytes(value);
    fs->Write(info, 0, info->Length);
}

int main() {
    String* path = S"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, S"This is some text");
            AddText(fs, S"This is some more text,");
            AddText(fs, S"\r\nand this is on a new line");
            AddText(fs, S"\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++) {
                AddText(fs, __box(Convert::ToChar(i))->ToString());

                //Split the output at every 10th character.
                if (Math::IEEERemainder(Convert::ToDouble(i), 10) == 0) {
                    AddText(fs, S"\r\n");
                }
            }
        } __finally {
            if (fs) __try_cast<IDisposable*>(fs)->Dispose();
        }
    }

    //Open the stream and read it back.
    {
        FileStream* fs = File::OpenRead(path);
        try {
            Byte b[] = new Byte[1024];
            UTF8Encoding* temp = new UTF8Encoding(true);
            while (fs->Read(b,0,b->Length) > 0) {
                Console::WriteLine(temp->GetString(b));
            }
        } __finally {
            if (fs) __try_cast<IDisposable*>(fs)->Dispose();
        }
    }
}

[Visual Basic, C#, C++] 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();
    }
}

[C++] 
#using <mscorlib.dll>

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

int main() {
    FileStream* fs = new FileStream(S"c:\\Variables.txt", FileMode::Append, FileAccess::Write, FileShare::Write);
    fs->Close();
    StreamWriter* sw = new StreamWriter(S"c:\\Variables.txt", true, Encoding::ASCII);
    String* NextLine=S"This is the appended line.";
    sw->Write(NextLine);
    sw->Close();
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.IO

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

FileStream Members | System.IO Namespace | File | FileAccess | FileMode | FileShare | Working with I/O | Reading Text from a File | Writing Text to a File | Basic File I/O | Reading and Writing to a Newly Created Data File

Show:
© 2014 Microsoft