C# FileStream CopyToAsync(Stream)

In this chapter you will learn:

  1. Get to know FileStream.CopyToAsync(Stream)
  2. Syntax for FileStream.CopyToAsync(Stream)
  3. Parameter for FileStream.CopyToAsync(Stream)
  4. Returns for FileStream.CopyToAsync(Stream)
  5. Example - FileStream.CopyToAsync(Stream)

Description

FileStream CopyToAsync(Stream) Asynchronously reads the bytes from the current stream and writes them to another stream.

Syntax

FileStream.CopyToAsync(Stream) has the following syntax.


[ComVisibleAttribute(false)]// www.  java  2s. c o  m
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public Task CopyToAsync(
  Stream destination
)

Parameters

FileStream.CopyToAsync(Stream) has the following parameters.

  • destination - The stream to which the contents of the current stream will be copied.

Returns

FileStream.CopyToAsync(Stream) method returns A task that represents the asynchronous copy operation.

Example

The following example demonstrates how to use two FileStream objects to asynchronously copy the files from one directory to another.


//w  w  w .  ja va 2 s .  c  o  m

using System;
using System.Threading.Tasks;

using System.IO;

public class MainWindow
{
    public static void Main() { }
    public MainWindow()
    {
        string StartDirectory = @"c:\start";
        string EndDirectory = @"c:\end";

        foreach (string filename in Directory.EnumerateFiles(StartDirectory))
        {
            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                {
                    await SourceStream.CopyToAsync(DestinationStream);
                }
            }
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know FileStream.CopyToAsync(Stream, Int32)
  2. Syntax for FileStream.CopyToAsync(Stream, Int32)
  3. Parameter for FileStream.CopyToAsync(Stream, Int32)
  4. Returns for FileStream.CopyToAsync(Stream, Int32)
  5. Example - FileStream.CopyToAsync(Stream, Int32)