C# FileStream ReadAsync(Byte[], Int32, Int32)

In this chapter you will learn:

  1. Get to know FileStream.ReadAsync(Byte[], Int32, Int32)
  2. Syntax for FileStream.ReadAsync(Byte[], Int32, Int32)
  3. Parameter for FileStream.ReadAsync(Byte[], Int32, Int32)
  4. Returns for FileStream.ReadAsync(Byte[], Int32, Int32)
  5. Example - FileStream.ReadAsync(Byte[], Int32, Int32)

Description

FileStream ReadAsync(Byte[], Int32, Int32) Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Syntax

FileStream.ReadAsync(Byte[], Int32, Int32) has the following syntax.


[ComVisibleAttribute(false)]/*from ww  w.  j  a v  a 2  s.  c  o m*/
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public Task<int> ReadAsync(
  byte[] buffer,
  int offset,
  int count
)

Parameters

FileStream.ReadAsync(Byte[], Int32, Int32) has the following parameters.

  • buffer - The buffer to write the data into.
  • offset - The byte offset in buffer at which to begin writing data from the stream.
  • count - The maximum number of bytes to read.

Returns

FileStream.ReadAsync(Byte[], Int32, Int32) method returns <

Example

The following example shows how to read from a file asynchronously.


/*from   w w w  .  j  a v  a2  s.  c  o  m*/
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;

public class MainWindow
{
    public static void Main(){}
    public MainWindow()
    {
        UnicodeEncoding uniencoding = new UnicodeEncoding();
        string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";
        byte[] result;

        using (FileStream SourceStream = File.Open(filename, FileMode.Open))
        {
            result = new byte[SourceStream.Length];
            await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
        }
        Console.WriteLine(uniencoding.GetString(result));
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know FileStream.ReadByte
  2. Syntax for FileStream.ReadByte
  3. Returns for FileStream.ReadByte
  4. Example - FileStream.ReadByte