File Handling in CSharp
Back to: C# .NET Tutorial
File Handling in C#
File handling in C# is crucial for managing and manipulating file operations efficiently. This comprehensive lesson delves into various aspects of file handling, including reading, writing, copying, and deleting files, providing a thorough understanding of these file operations through detailed code examples.
Reading from a File
Reading data from a file is a fundamental file handling operation. The StreamReader class facilitates reading text from a file, as shown in the following example:
using System; using System.IO; class Program { static void Main() { using (StreamReader reader = new StreamReader("example.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
Writing to a File
Writing data to a file is essential for data persistence. The StreamWriter class allows seamless writing to a file, as demonstrated in the following example:
using System; using System.IO; class Program { static void Main() { using (StreamWriter writer = new StreamWriter("example.txt")) { writer.WriteLine("Hello, File Handling!"); } } }
Copying a File
Copying files is a common file handling operation. The File class in C# enables easy file copying, as illustrated below:
using System; using System.IO; class Program { static void Main() { string sourceFile = "example.txt"; string destinationFile = "example_copy.txt"; File.Copy(sourceFile, destinationFile); } }
Deleting a File
Deleting files is essential for managing file resources. The File class allows simple file deletion, as shown in the example below:
using System; using System.IO; class Program { static void Main() { string fileToDelete = "example.txt"; File.Delete(fileToDelete); } }
Mastering these file handling operations is vital for efficient file management and manipulation in C#. By utilizing these techniques, developers can ensure smooth file handling and streamlined file system operations within their applications.