Iron Academy Logo
Learn C#

C# Read and Write File

Tim Corey
24m 34s

File input and output (I/O) operations in C# are an essential part of many software applications, allowing developers to read from and write to files efficiently. Whether you're storing data, logging application events, or processing large amounts of text or binary data, C# provides robust tools for working with files. In his video, "C# Data Access: Text Files," Tim Corey offers a detailed walkthrough of these file operations, focusing on how to use text files for both data storage and retrieval. This article aims to summarize the key concepts and techniques Tim covers in the video, providing you with practical insights into file I/O operations in C#.

Introduction

In C#, file input and output operations are essential for reading from and writing to text files. The File class provides static methods to interact with existing files or create new ones. StreamReader and StreamWriter are commonly used for reading and writing files. StreamReader reads files line by line, allowing you to access each line of text or an array of strings. You can also use the while loop to read larger files efficiently. The StreamWriter class is used to write data to a file, supporting writing strings and arrays. It can be used to append text to an existing file or overwrite the entire file. Methods like WriteText and WriteLine allow for easy data manipulation within text files.

These operations are typically performed in the static void Main method, where you define the file path. For instance, you can specify a filename and use StreamWriter to write a single string or an entire string array. The using statement ensures that the file is properly closed after operations, preventing resource leaks. StreamReader can also be used to read files line by line, and exceptions can be handled to manage potential errors when the file doesn't exist or cannot be accessed. These file I/O capabilities make C# an excellent choice for working with files efficiently and effectively.

Tim introduces the topic by highlighting the simplicity of reading from and writing to text files in C#. He demonstrates how a few lines of code can achieve these tasks, making text files a viable option for data storage.

Creating a Demo Console Application

Tim starts by creating a new console application named "TextFileDataAccessDemo" using Visual Studio.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace TextFileDataAccessDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }
}
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace TextFileDataAccessDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }
}

He explains the use of Console.ReadLine to keep the console window open, allowing users to see the output.

Reading from a Text File

Tim demonstrates how to read from a text file using the File.ReadAllLines method. He shows how to handle file paths and use string literals to avoid escape characters.

string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();
string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();

The File.ReadAllLines method reads all lines from the specified file and returns them as an array of strings. Tim converts this array to a list for easier manipulation.

Writing to a Text File

Tim explains how to write data to a text file using the File.WriteAllLines method. He demonstrates how to add new lines to the list and write the updated list back to the file.

lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);
lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);

This code adds a new entry to the list and writes the entire list back to the file.

Creating a Data Model and Populating it from a File

Tim creates a Person class to represent the data structure for each entry in the text file.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string URL { get; set; }
}
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string URL { get; set; }
}

He then reads the file and populates a list of Person objects.

List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();

foreach (string line in lines)
{
    string[] entries = line.Split(',');
    Person newPerson = new Person
    {
        FirstName = entries[0],
        LastName = entries[1],
        URL = entries[2]
    };
    people.Add(newPerson);
}
List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();

foreach (string line in lines)
{
    string[] entries = line.Split(',');
    Person newPerson = new Person
    {
        FirstName = entries[0],
        LastName = entries[1],
        URL = entries[2]
    };
    people.Add(newPerson);
}

This code reads each line, splits it by commas, and creates a Person object with the extracted data.

String Interpolation

Tim introduces string interpolation, a feature in C# 6.0 that simplifies the process of combining variables and strings. This method uses the $ symbol before the string and curly braces {} to embed variables directly within the string.

foreach (var person in people)
{
    Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}
foreach (var person in people)
{
    Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}

This syntax is more concise and efficient compared to traditional concatenation using the + operator.

Csharp Read Write File 1 related to String Interpolation

Data Validation

Tim emphasizes the importance of validating data when reading from a text file. He points out the risks of assuming the structure of data and recommends checking the length of the split entries.

foreach (string line in lines)
{
    string[] entries = line.Split(',');
    if (entries.Length == 3)
    {
        Person newPerson = new Person
        {
            FirstName = entries[0],
            LastName = entries[1],
            URL = entries[2]
        };
        people.Add(newPerson);
    }
    else
    {
        // Handle error
        Console.WriteLine("Invalid data format.");
    }
}
foreach (string line in lines)
{
    string[] entries = line.Split(',');
    if (entries.Length == 3)
    {
        Person newPerson = new Person
        {
            FirstName = entries[0],
            LastName = entries[1],
            URL = entries[2]
        };
        people.Add(newPerson);
    }
    else
    {
        // Handle error
        Console.WriteLine("Invalid data format.");
    }
}

This ensures that only lines with the correct number of entries are processed, avoiding potential runtime errors.

Adding Objects to a List

Tim demonstrates how to add new objects to the list. He uses an anonymous instance of the Person class to add a new person to the list.

people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });
people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });

This creates and initializes a new Person object in a single line, which is then added to the people list.

Writing Data Back to a Text File

Tim explains how to write the list of Person objects back to the text file. He converts the list of Person objects to a list of strings, where each string represents a line in the file.

List<string> output = new List<string>();
foreach (var person in people)
{
    output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);
List<string> output = new List<string>();
foreach (var person in people)
{
    output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);

This code iterates over the people list, creates a CSV string for each Person object, and writes the list of strings to the file.

Conclusion

Tim Corey’s detailed guide on file I/O operations in C# provides practical insights into reading from and writing to text files. By following his examples, developers can effectively manage data using text files and implement robust data storage solutions. For an in-depth understanding and hands-on learning experience, I highly encourage you to watch Tim Corey’s video, where he dives deeper into these concepts with real-world examples.