Moving File in Different Folder Programmatically in .NET Core

How to move file from one folder to another folder or in different folder programmatically in .net core using c#.net. method File.Move() to move file.
In today's article will show a simple tutorial with example for moving files from one folder to another in .net 8 core using c#.net. Here will use System.IO - File.Move() Method to move files from one folder to another folder programmatically in .net core using c#.net. 

Now for this article first we will create two folders and in this in first folder we will add some test file and second folder we will keep blank. In this blank folder we will move all he files from folder one to folder two.

Two folders
Here we are having folder One and Two. In this i have added some files in folder One. Have a look below. 
Files in Folder

Here in Folder One, we are having 3 files. Now let's check the code to move the files from folder one to folder two.
 string pathOne = "C:\\Personal\\Codemantra99.com\\One";
string pathTwo = "C:\\Personal\\Codemantra99.com\\Two";

if (!Path.Exists(pathOne))
{
    Console.WriteLine("pathOne does not exists.");
    return;
}
if (!Path.Exists(pathTwo))
{
    Directory.CreateDirectory(pathTwo);
}
int fileCountOne = Directory.GetFiles(pathOne).Count();
Console.WriteLine($"Total File Found in Folder One: {fileCountOne}");
int fileCountTwo = Directory.GetFiles(pathTwo).Count();
Console.WriteLine($"Total File Found in Folder Two: {fileCountTwo}");

foreach (string file in Directory.GetFiles(pathOne))
{
    File.Move(file, $"{pathTwo}\\{Path.GetFileName(file)}");
}
int fileNewCountOne = Directory.GetFiles(pathOne).Count();
Console.WriteLine($"Total File Found in Folder One afeter moving: {fileNewCountOne}");
int fileNewCountTwo = Directory.GetFiles(pathTwo).Count();
Console.WriteLine($"Total File Found in Folder Two after moving: {fileNewCountTwo}"); 
Here in above code, I have defined two variables of string type. In this I have added path for both the folders.  In next line I have validated path one is valid or not by using Path.Exists() method. If path is not valid it will return and break further processing. Now I have validated folder Tow. If it does not exist system will create the folder by using Directory.CreateDirectory() method.  

In very next line I have calculated the no of file exists in both the folders.  Now I have used look to read all the files by using Directory.GetFiles() method. after reading files I have used foreach loop to read each file and by using File.Move(file, path); to move the file in second or designation folder. Here I have used Path.GetFileName(file) to get only the file name. Now let's run the code to check the output. 

File move from one folder to another

Now let's check the check the folder Two. 

File moved

Post a Comment