A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 9.2 : File I/O - Working with directories

 in C# using File I/O. In C#, the System.IO namespace provides classes for working with files and directories. Here's a basic tutorial on how to perform common operations with directories:

1. Creating a Directory:

You can use the Directory.CreateDirectory method to create a new directory. Here's an example:

using System; using System.IO; class Program { static void Main() { string path = @"C:\MyDirectory"; // Check if the directory doesn't exist before creating it if (!Directory.Exists(path)) { Directory.CreateDirectory(path); Console.WriteLine("Directory created successfully."); } else { Console.WriteLine("Directory already exists."); } } }

2. Getting the Files in a Directory:

You can use the Directory.GetFiles method to get a list of files in a directory. Here's an example:

using System; using System.IO; class Program { static void Main() { string path = @"C:\MyDirectory"; // Check if the directory exists before getting files if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path); Console.WriteLine("Files in the directory:"); foreach (string file in files) { Console.WriteLine(file); } } else { Console.WriteLine("Directory does not exist."); } } }

3. Getting the Directories in a Directory:

You can use the Directory.GetDirectories method to get a list of subdirectories in a directory. Here's an example:

using System; using System.IO; class Program { static void Main() { string path = @"C:\MyDirectory"; // Check if the directory exists before getting subdirectories if (Directory.Exists(path)) { string[] subdirectories = Directory.GetDirectories(path); Console.WriteLine("Subdirectories in the directory:"); foreach (string subdirectory in subdirectories) { Console.WriteLine(subdirectory); } } else { Console.WriteLine("Directory does not exist."); } } }

4. Deleting a Directory:

You can use the Directory.Delete method to delete a directory. Here's an example:

using System; using System.IO; class Program { static void Main() { string path = @"C:\MyDirectory"; // Check if the directory exists before deleting it if (Directory.Exists(path)) { Directory.Delete(path); Console.WriteLine("Directory deleted successfully."); } else { Console.WriteLine("Directory does not exist."); } } }

Remember to handle exceptions appropriately, especially when working with file I/O operations, as they may throw exceptions for various reasons (e.g., insufficient permissions, file not found, etc.).