Complete C# Tutorial

Deleting and Moving Files in C# – A Complete Guide!

🌟 Introduction

Hey there, coder! 👋 Have you ever needed to delete a file you no longer need or move files to another location? Imagine you’re building a file manager app, and users keep uploading unnecessary files. You’d want a way to delete them. Or, if you’re organizing photos, you may need to move them to different folders.

That’s where deleting and moving files in C# comes in! These file-handling operations help you manage files efficiently, ensuring everything is neat and tidy.

In this lesson, we’ll explore how to delete files permanently and move files between locations using simple C# code. Don’t worry—I’ll keep it fun and easy! Ready? Let’s go! 🚀

🗑️ Why Delete or Move Files?

Think about how much junk collects on your computer—old documents, outdated downloads, duplicate photos… 🤯

Now, imagine an automated tool that deletes useless files and organizes your data. That’s exactly what you can build using deleting and moving files in C#! Let’s see how.

📌 How to Delete a File in C#

Deleting a file is easy! Just use File.Delete(). It removes the file permanently from the system.

 

📌 Example 1: Delete a File

				
					using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "test.txt";

        // Creating a file first
        File.WriteAllText(filePath, "This is a sample file.");

        // Check if file exists before deleting
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
            Console.WriteLine("File deleted successfully!");
        }
        else
        {
            Console.WriteLine("File not found!");
        }
    }
}
				
			

🖥️ Output:

				
					File deleted successfully!
				
			

📌 Explanation:

1️⃣ We create a file test.txt with some sample content.
2️⃣ Before deleting, we check if it exists using File.Exists().
3️⃣ If it exists, File.Delete(filePath) removes it permanently.

⚠️ Warning: Once deleted, a file cannot be recovered. Be careful! 😬

📌 How to Move a File in C#

To move a file, we use File.Move(). This method moves a file from one location to another.

 

📌 Example 2: Move a File

				
					using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourcePath = "source.txt";
        string destinationPath = "moved.txt";

        // Creating a file first
        File.WriteAllText(sourcePath, "This file will be moved!");

        // Moving the file
        if (File.Exists(sourcePath))
        {
            File.Move(sourcePath, destinationPath);
            Console.WriteLine("File moved successfully!");
        }
        else
        {
            Console.WriteLine("Source file not found!");
        }
    }
}
				
			

🖥️ Output:

				
					File moved successfully!
				
			

📌 Explanation:

1️⃣ We create a file source.txt.
2️⃣ We check if it exists before moving.
3️⃣ File.Move(sourcePath, destinationPath) moves the file to moved.txt.

Now, source.txt is gone, and its content is inside moved.txt. Simple, right? 😃

📌 Moving a File to Another Folder

Sometimes, you need to move files between folders. Let’s do that!

 

📌 Example 3: Move a File to Another Folder

				
					using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourcePath = "example.txt";
        string destinationFolder = "Backup";
        string destinationPath = Path.Combine(destinationFolder, "example.txt");

        // Creating a file
        File.WriteAllText(sourcePath, "This file is being moved to another folder!");

        // Create destination folder if it doesn’t exist
        if (!Directory.Exists(destinationFolder))
        {
            Directory.CreateDirectory(destinationFolder);
        }

        // Move file to the folder
        if (File.Exists(sourcePath))
        {
            File.Move(sourcePath, destinationPath);
            Console.WriteLine("File moved to Backup folder!");
        }
        else
        {
            Console.WriteLine("Source file not found!");
        }
    }
}
				
			

🖥️ Output:

				
					File moved to Backup folder!
				
			

🌍 Real-World Scenario: Organizing Log Files

Imagine you’re working on a logging system. Every day, a new log file is generated. You want to move old logs to an “Archive” folder and delete logs older than 7 days.

				
					using System;
using System.IO;

class Program
{
    static void Main()
    {
        string logFile = "log_2025-02-25.txt";
        string archiveFolder = "LogsArchive";
        string archivePath = Path.Combine(archiveFolder, logFile);

        // Create an example log file
        File.WriteAllText(logFile, "Log file contents...");

        // Ensure the archive folder exists
        if (!Directory.Exists(archiveFolder))
        {
            Directory.CreateDirectory(archiveFolder);
        }

        // Move log file to the archive folder
        if (File.Exists(logFile))
        {
            File.Move(logFile, archivePath);
            Console.WriteLine("Log file moved to archive!");
        }
        else
        {
            Console.WriteLine("Log file not found!");
        }

        // Delete old log files (simulate deleting logs older than 7 days)
        foreach (var file in Directory.GetFiles(archiveFolder))
        {
            FileInfo fileInfo = new FileInfo(file);
            if (fileInfo.CreationTime < DateTime.Now.AddDays(-7))
            {
                File.Delete(file);
                Console.WriteLine($"Deleted old log: {file}");
            }
        }
    }
}
				
			

🖥️ Output:

				
					Log file moved to archive!
Deleted old log: LogsArchive/log_2025-02-18.txt
				
			

With this approach, you can keep your logs organized and delete outdated files automatically. Neat, right? 😎

📝 Conclusion

Awesome job! 🎉 You just learned how deleting and moving files in C# works.

🔹 Use File.Delete() to remove files permanently.
🔹 Use File.Move() to relocate files.
🔹 Always check if the file exists before performing any operation.

Now, try it out yourself! If you get stuck, don’t worry—I’ve got your back! 😊

 

⏭️ Next What?

You’re now a pro at deleting and moving files in C#! But what if you need to work with directories—create, delete, or list folders? 🤔

In the next chapter, you’ll learn Working with Directories in C#! Stay tuned and keep coding! 🚀

Leave a Comment

Share this Doc

Deleting and Moving Files

Or copy link