C# StreamReader ReadAsync

In this chapter you will learn:

  1. Get to know StreamReader.ReadAsync
  2. Syntax for StreamReader.ReadAsync
  3. Parameter for StreamReader.ReadAsync
  4. Returns for StreamReader.ReadAsync
  5. Example - StreamReader.ReadAsync

Description

StreamReader ReadAsync Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.

Syntax

StreamReader.ReadAsync has the following syntax.


[ComVisibleAttribute(false)]/*from   w w  w.j av a2s. c o m*/
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public override Task<int> ReadAsync(
  char[] buffer,
  int index,
  int count
)

Parameters

StreamReader.ReadAsync has the following parameters.

  • buffer - 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 - The position in buffer at which to begin writing.
  • count - The maximum number of characters to read. If the end of the stream is reached before the specified number of characters is written into the buffer, the current method returns.

Returns

StreamReader.ReadAsync method returns <

Example

The following example shows how to read all the characters in a file by using the ReadAsync(Char[], Int32, Int32) method. \


using System;//from  w  ww. ja va2 s. c  o  m
using System.IO;
using System.Text;

using System;
public class MainClass{
  public static void Main(String[] argv){  
      string filename = @"C:\Example\existingfile.txt";
      char[] result;
      StringBuilder builder = new StringBuilder();

      using (StreamReader reader = File.OpenText(filename))
      {
          result = new char[reader.BaseStream.Length];
          await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
      }

      foreach (char c in result)
      {
          if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c))
          {
              builder.Append(c);
          }
      }
      Console.WriteLine(builder.ToString());

  }
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know StreamReader.ReadBlock
  2. Syntax for StreamReader.ReadBlock
  3. Parameter for StreamReader.ReadBlock
  4. Returns for StreamReader.ReadBlock
  5. Example - StreamReader.ReadBlock