Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

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 Tim Corey's video, "C# Data Access: Text Files," he 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#.
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 WriteLine and WriteText allow for easy data manipulation within text files.
These operations are typically performed within 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.
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(); // Keeps the console window open to view the output
}
}
}Imports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Linq
Namespace TextFileDataAccessDemo
Class Program
Shared Sub Main(ByVal args As String())
Console.ReadLine() ' Keeps the console window open to view the output
End Sub
End Class
End NamespaceHe explains the use of Console.ReadLine to keep the console window open, allowing users to see the output.
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();Dim filePath As String = "C:\demos\test.txt"
Dim lines As List(Of String) = 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.
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.
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 Property FirstName As String
Public Property LastName As String
Public Property URL As String
End ClassHe 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);
}Dim people As New List(Of Person)()
Dim lines As List(Of String) = File.ReadAllLines(filePath).ToList()
For Each line As String In lines
Dim entries As String() = line.Split(","c)
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
NextThis code reads each line, splits it by commas, and creates a Person object with the extracted data.
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}");
}For Each person In people
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}")
NextThis syntax is more concise and efficient compared to traditional concatenation using the + operator.

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.");
}
}For Each line As String In lines
Dim entries As String() = line.Split(","c)
If entries.Length = 3 Then
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
Else
' Handle error
Console.WriteLine("Invalid data format.")
End If
NextThis ensures that only lines with the correct number of entries are processed, avoiding potential runtime errors.
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 With {.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.
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);Dim output As New List(Of String)()
For Each person In people
output.Add($"{person.FirstName},{person.LastName},{person.URL}")
Next
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.
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.
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
Join our newsletter, you’ll get exclusive access on article updates. We value your privacy