HOW TO COPY A FILE USING C#

Hi, in this post I'll explain you an easy way of copy paste a file using the C# language.
The next example will be shown using Microsoft Visual Studio 2008, but this example can be done with whatever ide you prefer.


STEP 1: Create a Console Application. (for quick demonstration purposes)

STEP 2: THE CODE.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HOWTO_COPY
{
    class Program
    {
        static void Main(string[] args)
        {
            //the try below will manage IOExceptions.
            try
            {
                //creates and fill the bytes array with the data.
                byte[] readBuffer = System.IO.File.ReadAllBytes(@"C:\directory\ORIGINAL-FILE.txt");

                //finally we do the writing of the bytes array back to a new file.
                //(this will overwrite any existing file matching the filename).
                System.IO.File.WriteAllBytes(@"C:\directory\COPIED-FILE.txt", readBuffer);
                Console.WriteLine("FILE SUCCESSFULLY CREATED");
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
            //the lines below will freeze the console so you see the output.
            Console.WriteLine("\n\nEND - | C# Quick Examples |");
            Console.ReadLine();
        }
    }
}

SCREENSHOTS

Create the Console Application Project.




Only one file in that directory "C:\directory\"

Running the Application.
File successfully copied, same size, (the data is also the same).



See you in the next example.

No comments:

Post a Comment

2 ads