C# provides powerful classes for working with files and directories, making file system operations straightforward and efficient. The File and Directory classes are essential tools for developers who need to manage files and folders in their applications.
The File class offers static methods for creating, copying, deleting, moving, and opening files. It's part of the System.IO namespace and provides a simple way to perform common file operations.
using System.IO;
// Create a new file
File.Create("example.txt");
// Write text to a file
File.WriteAllText("example.txt", "Hello, World!");
// Read text from a file
string content = File.ReadAllText("example.txt");
// Copy a file
File.Copy("example.txt", "copy.txt");
// Delete a file
File.Delete("copy.txt");
These operations are just a few examples of what you can do with the File class. It's important to note that these methods are best suited for smaller files, as they load the entire file into memory.
The Directory class provides static methods for creating, moving, and enumerating through directories and subdirectories. Like the File class, it's part of the System.IO namespace.
using System.IO;
// Create a new directory
Directory.CreateDirectory("NewFolder");
// Get files in a directory
string[] files = Directory.GetFiles("NewFolder");
// Get subdirectories
string[] subdirectories = Directory.GetDirectories("NewFolder");
// Move a directory
Directory.Move("NewFolder", "MovedFolder");
// Delete a directory
Directory.Delete("MovedFolder", true); // true for recursive delete
The Directory class is invaluable when you need to manage folders and their contents programmatically. It simplifies tasks like creating backup systems or organizing files based on certain criteria.
To further enhance your file handling skills in C#, explore these related topics:
By mastering the File and Directory classes, you'll be well-equipped to handle a wide range of file system tasks in your C# applications. Remember to always consider performance and security implications when working with files and directories.