Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

StreamReader.Read Method ()


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

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

public override int Read()

Return Value

Type: System.Int32

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

Exception Condition

An I/O error occurs.

This method overrides TextReader.Read.

This method returns an integer so that it can return -1 if the end of the stream has been reached. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.

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

The following code example demonstrates a simple use of the Read method.

using System;
using System.IO;

class Test 

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

            if (File.Exists(path)) 

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

            using (StreamReader sr = new StreamReader(path)) 
                while (sr.Peek() >= 0) 
        catch (Exception e) 
            Console.WriteLine("The process failed: {0}", e.ToString());

The following code example demonstrates reading a single character using the Read() method overload, formatting the ASCII integer output as decimal and hexadecimal.

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

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
© 2016 Microsoft