How to Copy a File from One Location to Another in C#.NET?

How to copy or move file form source directory or folder or location to designation folder or directory in .net core using c#.net. Copy past file.
In today's article I will show you a simple tutorial with example that how to copy file from one folder to another folder or directory or one location to another location in .NET core using C#.net. File.Copy method is used for moving file from one directory to another. First, we will create source and designation folder as shown below.

Source Designation Folder

Now let's add some file in the source folder which we will move to designation folder. 
Source Folder
After creating the folder, we will use .NET core console application to perform the example. Now let's create a console application.
string source = "<Source Path>";
string destignation = "<Designation Path>";
try
{
    List<string> filelist = new List<string>();
    filelist = Directory.GetFiles(source).ToList();
    foreach (string file in filelist)
    {
        string fileName = Path.GetFileName(file);
        File.Copy(Path.Combine(source, fileName), Path.Combine(destignation, fileName), true);
    }
    Console.WriteLine("Total File Moved: " + filelist.Count);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
} 
In above code first we have defined two string variables. First is for source folder and second one is designation folder. After that I have defined try catch block to handle exception while moving the file. Now to read all the file from source directory I have used Directory.GetFiles

After getting file list I have used foreach to move each file one by one. Inside the foreach look I have used Path.GetFileName to get the file name. After getting the file name to copy the file form one directory to another is File.Copy method.  At the end I have displayed the total no of files count. Now let's run the code to check the output. 

Total File Count

As shown above total file count is 3 in source folder. Now let's press F5 to check the output.

Total File Count

Now let's check the designation folder.

Designation Folder

Post a Comment