Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System.IO Namespace
StreamReader Class
 ReadToEnd Method
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
StreamReader..::.ReadToEnd Method

Updated: November 2007

Reads the stream from the current position to the end of the stream.

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

Visual Basic (Declaration)
Public Overrides Function ReadToEnd As String
Visual Basic (Usage)
Dim instance As StreamReader
Dim returnValue As String

returnValue = instance.ReadToEnd()
C#
public override string ReadToEnd()
Visual C++
public:
virtual String^ ReadToEnd() override
J#
public String ReadToEnd()
JScript
public override function ReadToEnd() : String

Return Value

Type: System..::.String

The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns the empty string("").

ExceptionCondition
OutOfMemoryException

There is insufficient memory to allocate a buffer for the returned string.

IOException

An I/O error occurs.

This method overrides TextReader..::.ReadToEnd.

ReadToEnd works best when you need to read all the input from the current position to the end of the stream. If more control is needed over how many characters are read from the stream, use the Read(array<Char>[]()[], Int32, Int32) method overload, which generally results in better performance.

ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols, in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely and should be avoided.

Note than when using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. If the size of the buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes).

If the current method throws an OutOfMemoryException, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. Since the position of the reader in the stream cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the StreamReader object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream object also needs to be reinitialized.

To avoid such a situation and produce robust code you should use the Read method and store the read characters in a pre-allocated buffer.

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

The following code example reads all the way to the end of a file in one operation.

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"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            'This allows you to do one Read operation.
            Console.WriteLine(sr.ReadToEnd())
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

C#
using System;
using System.IO;

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

        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path)) 
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path)) 
            {
                //This allows you to do one Read operation.
                Console.WriteLine(sr.ReadToEnd());
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

Visual C++
using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         //This allows you to do one Read operation.
         Console::WriteLine( sr->ReadToEnd() );
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}

J#
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";

        try {
            if (File.Exists(path)) {
                File.Delete(path);
            }
            StreamWriter sw = new StreamWriter(path);
            try {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }
            finally {
                sw.Dispose();
            }
            StreamReader sr = new StreamReader(path);
            try {
                //This allows you to do one Read operation.
                Console.WriteLine(sr.ReadToEnd());
            }
            finally {
                sr.Dispose();
            }
        }
        catch (System.Exception e) {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    } //main
} //Test

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

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

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
ReadToEnd() reading issues      JSiddharth ... phil.alverson   |   Edit   |  

The following code path has unexpected results
string line ;
FileInfo albumitem = file of length 10Mb
StreamReader fileStream = newStreamReader(albumitem.Directory+"\\"+albumitem.Name)
line = fileStream.ReadToEnd()
Console.WriteLine(albumitem.Length-line.Length)
The above prints a nonzero value. Any guidance will be helpful


[pma 6/30/2008] StreamReader uses an Encoding (which you can choose in the constructor if desired) to translate the raw input byte array read from its underlying stream into a character array, which is then returned as a string in the ReadToEnd() method. Unicode encodings may use up to 4 bytes to specify a single character, so it's very likely that you will have less characters in your string than bytes in your stream (meaning you would get a positive integer from albumitem.Length-line.Length).

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker