Introduction To File: Input-Output

Lesson 5.3: Introduction to File Input/Output


So far, you've learned how to interact with the user through the console. In this lesson, you'll discover how to read data from files and write data to files, opening up a whole new world of possibilities for your C# programs.


Why Work with Files?


Persistent Storage: Files allow you to store data that persists even after your program ends. This is crucial for saving user preferences, configurations, high scores, and more.

Data Exchange: Files are a common way to exchange data between different programs or systems.

Large Datasets: Working with files allows you to process large amounts of data that wouldn't fit in memory.

Key Concepts


Streams:

In C#, file I/O operations are performed using streams.

A stream is a sequence of bytes that can be read from or written to.

Think of a stream as a pipe through which data flows.

Text Files vs. Binary Files:

Text Files: Contain human-readable characters (letters, numbers, symbols).

Binary Files: Contain raw data that might not be directly readable by humans (e.g., images, music, executable programs).

Reading from a Text File


C#

using System;

using System.IO; // Necessary for file I/O


string filePath = "data.txt";


try

{

    // Read all lines from the file into a string array

    string[] lines = File.ReadAllLines(filePath);


    foreach (string line in lines)

    {

        Console.WriteLine(line);

    }

}

catch (FileNotFoundException)

{

    Console.WriteLine("File not found.");

}


Writing to a Text File


C#

string filePath = "output.txt";

string[] dataToWrite = { "Line 1", "Line 2", "Line 3" };


File.WriteAllLines(filePath, dataToWrite); // Creates or overwrites the file


File Paths: Always specify the correct path to the file you want to work with.

Error Handling: Use try-catch blocks to handle file-related exceptions (e.g., FileNotFoundException, IOException).

File Encoding: When working with text files, specify the correct encoding (e.g., UTF-8) to avoid garbled characters.

Stream Disposal: Always close streams when you're finished with them to free up resources. You can use using blocks for automatic disposal:

C#

using (StreamReader reader = new StreamReader(filePath))

{

    string line;

    while ((line = reader.ReadLine()) != null)

    {

        // Process the line

    }

} // The StreamReader is automatically closed here

Hands-On Exercise


Create a text file named names.txt and write a few names into it, each on a separate line.

Write a C# program that reads the names from the file and prints them to the console, adding a greeting to each name (e.g., "Hello, Alice!").

Extend the program to prompt the user for a new name, and then append that name to the end of the file.

This exercise will give you a basic understanding of reading and writing text files, setting you on the path to more advanced file I/O operations in C#.

Course Syllabus