Here's a basic tutorial on File I/O (Input/Output) in C# for reading from and writing to files. File I/O is an essential part of many applications for tasks such as storing and retrieving data, configuration settings, and more.
Reading from Files:
Step 1: Import Necessary Namespace
using System;using System.IO;
Step 2: Reading Text from a File
class Program{static void Main(){// Specify the path to the filestring filePath = "path/to/your/file.txt";// Check if the file existsif (File.Exists(filePath)){// Read all lines from the file into an arraystring[] lines = File.ReadAllLines(filePath);// Display the content of the fileforeach (string line in lines){Console.WriteLine(line);}}else{Console.WriteLine("File not found");}}}
Step 3: Reading Binary Data from a File
class Program{static void Main(){string filePath = "path/to/your/file.bin";if (File.Exists(filePath)){// Read all bytes from the filebyte[] data = File.ReadAllBytes(filePath);// Process the binary data as needed// (e.g., convert to text, parse as specific format)}else{Console.WriteLine("File not found");}}}
Writing to Files:
Step 1: Import Necessary Namespace
using System;using System.IO;
Step 2: Writing Text to a File
class Program{static void Main(){string filePath = "path/to/your/output.txt";// Content to be written to the filestring content = "Hello, File I/O in C#!";// Write the content to the fileFile.WriteAllText(filePath, content);Console.WriteLine("File written successfully");}}
Step 3: Writing Binary Data to a File
class Program{static void Main(){string filePath = "path/to/your/output.bin";// Binary data to be written to the filebyte[] data = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // ASCII values for "Hello"// Write the binary data to the fileFile.WriteAllBytes(filePath, data);Console.WriteLine("File written successfully");}}
These examples cover basic file operations in C#. You can customize them based on your specific needs and handle exceptions to enhance the robustness of your file I/O operations.