Console App Task 01: Create Console Application that transfers folders from one location to another in C# ?
Here’s a C# Console Application that transfers folders from one location to another. The program considers folders created today up to the last one month before transferring them.
Features:
✅ Transfers folders based on creation date (last 30 days).
✅ Uses Directory
and File
classes to move folders.
✅ Displays progress messages in the console.
C# Console Application - Folder Transfer
using System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = @"C:\SourceFolder"; // Change to your source directory
string destinationPath = @"D:\DestinationFolder"; // Change to your destination directory
try
{
if (!Directory.Exists(sourcePath))
{
Console.WriteLine("Source directory does not exist!");
return;
}
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
DateTime oneMonthAgo = DateTime.Now.AddMonths(-1); // 30 days ago
string[] folders = Directory.GetDirectories(sourcePath);
foreach (string folder in folders)
{
DirectoryInfo dirInfo = new DirectoryInfo(folder);
if (dirInfo.CreationTime >= oneMonthAgo) // Check folder creation date
{
string targetFolder = Path.Combine(destinationPath, dirInfo.Name);
if (Directory.Exists(targetFolder))
{
Console.WriteLine($"Skipping: {dirInfo.Name} (Already exists)");
continue;
}
Directory.Move(folder, targetFolder);
Console.WriteLine($"Moved: {dirInfo.Name}");
}
}
Console.WriteLine("Folder transfer completed successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
How It Works:
- The program gets all folders in
sourcePath
. - It checks the creation date of each folder.
- If the folder was created in the last 30 days, it moves it to
destinationPath
. - If a folder already exists in the destination, it skips the transfer.
- If
destinationPath
does not exist, it creates it automatically.
Steps to Run:
- Open Visual Studio or Visual Studio Code.
- Create a new Console App (.NET Framework or .NET Core) project.
- Copy and paste the above code into
Program.cs
. - Change
sourcePath
anddestinationPath
as needed. - Run the program.
Example Folder Transfer
Before Running the Program:
C:\SourceFolder
├── FolderA (Created: Today)
├── FolderB (Created: 15 days ago)
├── FolderC (Created: 45 days ago)
After Running the Program:
D:\DestinationFolder
├── FolderA
├── FolderB
✅ FolderC was NOT moved because it was created more than 30 days ago.
If you like comment and share. 🚀
0 Comments