C# StreamReader ReadBlockAsync

In this chapter you will learn:

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

Description

StreamReader ReadBlockAsync 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.ReadBlockAsync has the following syntax.


[ComVisibleAttribute(false)]/*from www.  j  av  a2  s .  c om*/
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public override Task<int> ReadBlockAsync(
  char[] buffer,
  int index,
  int count
)

Parameters

StreamReader.ReadBlockAsync 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 method returns.

Returns

StreamReader.ReadBlockAsync method returns <

Example


using System;//from   w w  w  .  j  av a 2s. c  om
using System.IO;

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

        using (StreamWriter sw = new StreamWriter(path)) 
        {
            sw.WriteLine("This");
            sw.WriteLine("is from ");
            sw.WriteLine("java2s.com");
            sw.WriteLine(".");
        }

        using (StreamReader sr = new StreamReader(path)) 
        {
            char[] c = null;
            while (sr.Peek() >= 0) 
            {
                c = new char[5];
                sr.ReadBlockAsync(c, 0, c.Length);
                Console.WriteLine(c);
            }
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know StreamReader.ReadLine
  2. Syntax for StreamReader.ReadLine
  3. Returns for StreamReader.ReadLine
  4. Example - StreamReader.ReadLine