StreamReader.Read Method (System.IO) (2023)

  • Reference

Definition

Namespace:
System.IO
Assembly:
System.IO.dll
Assembly:
System.Runtime.dll
Assembly:
System.Runtime.Extensions.dll
Assembly:
mscorlib.dll
Assembly:
netstandard.dll

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Reads the next character or next set of characters from the input stream.

Overloads

Read()

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

Read(Span<Char>)

Reads the characters from the current stream into a span.

Read(Char[], Int32, Int32)

Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

Read()

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

public: override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer

Returns

Int32

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

Exceptions

IOException

An I/O error occurs.

Examples

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

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 { while ( sr->Peek() >= 0 ) { Console::Write( (Char)sr->Read() ); } } finally { delete sr; } } catch ( Exception^ e ) { Console::WriteLine( "The process failed: {0}", e ); }}
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()); } }}
Imports System.IOImports System.TextPublic 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 SubEnd Class

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

using namespace System;using namespace System::IO;int main(){ //Create a FileInfo instance representing an existing text file. FileInfo^ MyFile = gcnew 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();}
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(); }}
Imports System.IOClass 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 SubEnd Class

Remarks

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.

See also

  • File and Stream I/O
  • How to: Read Text from a File
  • How to: Write Text to a File

Applies to

Read(Span<Char>)

Reads the characters from the current stream into a span.

public: override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer

Parameters

buffer
Span<Char>

When this method returns, contains the specified span of characters replaced by the characters read from the current source.

Returns

Int32

The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the buffer length, depending on whether the data is available within the stream.

Exceptions

IOException

The number of characters read from the stream is larger than the buffer length.

ArgumentNullException

buffer is null.

Applies to

Read(Char[], Int32, Int32)

Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

public: override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

Parameters

buffer
Char[]

When this method returns, contains the specified character array with the values between index and (index + count - 1) replaced by the characters read from the current source.

index
Int32

The index of buffer at which to begin writing.

count
Int32

The maximum number of characters to read.

Returns

Int32

The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

Exceptions

ArgumentException

The buffer length minus index is less than count.

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

index or count is negative.

IOException

An I/O error occurs, such as the stream is closed.

Examples

The following code example reads five characters at a time until the end of the file is reached.

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 is an arbitrary size for this example. array<Char>^c = nullptr; while ( sr->Peek() >= 0 ) { c = gcnew array<Char>(5); sr->Read( c, 0, c->Length ); //The output will look odd, because //only five characters are read at a time. Console::WriteLine( c ); } } finally { delete sr; } } catch ( Exception^ e ) { Console::WriteLine( "The process failed: {0}", e ); }}
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 is an arbitrary size for this example. char[] c = null; while (sr.Peek() >= 0) { c = new char[5]; sr.Read(c, 0, c.Length); //The output will look odd, because //only five characters are read at a time. Console.WriteLine(c); } } } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } }}
Imports System.IOImports System.TextPublic 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 'This is an arbitrary size for this example. Dim c(5) As Char sr.Read(c, 0, c.Length) 'The output will look odd, because 'only five characters are read at a time. Console.WriteLine(c) Loop sr.Close() Catch e As Exception Console.WriteLine("The process failed: {0}", e.ToString()) End Try End SubEnd Class

Remarks

This method overrides TextReader.Read.

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

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, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). 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.

This method returns after either the number of characters specified by the count parameter are read, or the end of the file is reached. ReadBlock is a blocking version of Read.

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

See also

  • File and Stream I/O
  • How to: Read Text from a File
  • How to: Write Text to a File

Applies to

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated: 03/06/2023

Views: 6042

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.