C# FileStream CopyToAsync(Stream, Int32)

In this chapter you will learn:

  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)

Description

FileStream CopyToAsync(Stream, Int32) Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

Syntax

FileStream.CopyToAsync(Stream, Int32) has the following syntax.


[ComVisibleAttribute(false)]//w  w  w.j a  v a2 s. c  o m
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public Task CopyToAsync(
  Stream destination,
  int bufferSize
)

Parameters

FileStream.CopyToAsync(Stream, Int32) has the following parameters.

  • destination - The stream to which the contents of the current stream will be copied.
  • bufferSize - The size, in bytes, of the buffer. This value must be greater than zero. The default size is 4096.

Returns

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

Example


using System;//from   w ww .j a  va 2 s  .com
using System.Threading.Tasks;
using System.Windows;
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,200);
                }
            }
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know FileStream.Lock
  2. Syntax for FileStream.Lock
  3. Parameter for FileStream.Lock
  4. Returns for FileStream.Lock
  5. Example - FileStream.Lock