Working with Files and Input/Output in C#

January 7, 2024

This post teaches readers how to work with files and handle input/output operations in C#. It covers reading and writing files, as well as accepting user input and displaying output in the console.

Reading and Writing Files

In C#, you can easily read from and write to files using the System.IO namespace. To read from a file, you can use the StreamReader class, and to write to a file, you can use the StreamWriter class.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Reading from a file
        using (StreamReader reader = new StreamReader(<filePath>))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }

        // Writing to a file
        using (StreamWriter writer = new StreamWriter(<filePath>))
        {
            writer.WriteLine(<content>);
        }
    }
}

Accepting User Input

To accept user input in C#, you can use the Console.ReadLine() method. This method reads the next line of characters from the standard input stream.

string userInput = Console.ReadLine();
Console.WriteLine("You entered: " + userInput);

Displaying Output in the Console

To display output in the console, you can use the Console.WriteLine() method. This method writes the specified data, followed by the current line terminator, to the standard output stream.

Console.WriteLine("Hello, world!");