This documentation is archived and is not being maintained.

StreamReader.Read Method ()

.NET Framework 1.1

Reads the next character from the input stream and advances the character position by one character.

[Visual Basic]
Overrides Overloads Public Function Read() As Integer
[C#]
public override int Read();
[C++]
public: int Read();
[JScript]
public override function Read() : int;

Return Value

The next character from the input stream represented as an Int32, or -1 if no more characters are available.

Exceptions

Exception Type Condition
IOException An I/O error occurs.

Remarks

This method overrides Read.

This method returns an integer so that it can return -1 if the end of the stream has been reached.

For an example of using this method, 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

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

Example

[Visual Basic, C#, C++] The following example demonstrates a simple use of the Read method.

[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)

            Do While sr.Peek() >= 0
                Console.Write(Convert.ToChar(sr.Read()))
            Loop
            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)) 
            {
                while (sr.Peek() >= 0) 
                {
                    Console.Write((char)sr.Read());
                }
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

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

using namespace System;
using namespace System::IO;

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

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

      StreamWriter* sw = new StreamWriter(path);
      try {
         sw->WriteLine(S"This");
         sw->WriteLine(S"is some text");
         sw->WriteLine(S"to test");
         sw->WriteLine(S"Reading");
      } __finally {
         if (sw) __try_cast<IDisposable*>(sw)->Dispose();
      }

      StreamReader* sr = new StreamReader(path);
      try {
         while (sr->Peek() >= 0) {
            Console::Write((Char)sr->Read());
         }
      } __finally {
         if (sr) __try_cast<IDisposable*>(sr)->Dispose();
      }
   } catch (Exception* e) {
      Console::WriteLine(S"The process failed: {0}", e);
   }
}

[Visual Basic, C#, C++] The following example demonstrates reading a single character using StreamReader.Read(), formatting the ASCII integer output as decimal and hexadecimal.

[Visual Basic] 
Imports System
Imports System.IO

Class StrmRdrRead
   
   Public Shared Sub Main()
      'Create a FileInfo instance representing an existing text file.
      Dim MyFile As New FileInfo("c:\csc.txt")
      'Instantiate a StreamReader to read from the text file.
      Dim sr As StreamReader = MyFile.OpenText()
      'Read a single character.
      Dim FirstChar As Integer = sr.Read()
      'Display the ASCII number of the character read in both decimal and hexadecimal format.
      Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
      sr.Close()
   End Sub 'Main
End Class 'StrmRdrRead

[C#] 
using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}

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

using namespace System;
using namespace System::IO;

int main() {
    //Create a FileInfo instance representing an existing text file.
    FileInfo* MyFile = new FileInfo(S"c:\\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader* sr = MyFile->OpenText();
    //Read a single character.
    int FirstChar = sr->Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console::WriteLine(S"The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        __box(FirstChar), __box(FirstChar));
    //
    sr->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

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, Common Language Infrastructure (CLI) Standard

See Also

StreamReader Class | StreamReader Members | System.IO Namespace | StreamReader.Read Overload List | Working with I/O | Reading Text from a File | Writing Text to a File

Show: