File copier Learn programming C#



Lesson:

File Management


Exercise:

File copier


Objetive:

Create a program to copy a source file to a destination file. You must use FileStream and a block size of 512 KB. An example usage might be:

mycopy file.txt e:\file2.txt

The program should handle cases where the source file does not exist, and it should warn the user (but not overwrite) if the destination file already exists.


Code:

using System;
using System.IO;
public class FileCopier
{

    public static void Main()
    {
        const int BUFFER_SIZE = 512 * 1024;

        byte[] data = new byte[BUFFER_SIZE];

        FileStream inFile = File.OpenRead("1.exe");
        FileStream outFile = File.Create("1-copy.exe");

        int amountRead;

        do
        {
            amountRead = inFile.Read(data, 0, BUFFER_SIZE);
            outFile.Write(data, 0, amountRead);
        }
        while (amountRead == BUFFER_SIZE);

        inFile.Close();
        outFile.Close();
    }
}