Menu
Coddy logo textTech

Working with Files

Part of the Logic & Flow section of Coddy's C# journey — lesson 26 of 66.

In C#, you can work with files using classes from the System.IO namespace. The two main classes for text files are StreamReader (for reading) and StreamWriter (for writing).

Writing to a file:

using System.IO;

// Create a StreamWriter to write to a file
StreamWriter writer = new StreamWriter("myfile.txt");

// Write text to the file
writer.WriteLine("Hello, World!");
writer.WriteLine("This is line 2");

// Close the file
writer.Close();

Reading from a file:

using System.IO;

// Create a StreamReader to read from a file
StreamReader reader = new StreamReader("myfile.txt");

// Read all content from the file
string content = reader.ReadToEnd();
Console.WriteLine(content);

// Close the file
reader.Close();

Reading line by line:

StreamReader reader = new StreamReader("myfile.txt");

// Read first line
string line1 = reader.ReadLine();
Console.WriteLine(line1);

// Read second line
string line2 = reader.ReadLine();
Console.WriteLine(line2);

reader.Close();

Remember to always close your files with Close() when you're done!

challenge icon

Challenge

Easy

Create a method named ReadFile that:

  1. Takes one string parameter: filename
  2. Reads the content from the file using StreamReader
  3. Prints the content to the console
  4. Closes the reader

Try it yourself

using System;
using System.IO;

class Program
{
    public static void ReadFile(string filename)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        string filename = Console.ReadLine();
        ReadFile(filename);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow