Lesson 4
Writing Table Data to Files with C#
Introduction

Welcome to this lesson on writing table data to text files using C#. In today's digital world, storing and sharing data efficiently is essential. Text files are a common way to achieve this due to their simplicity and compatibility with various systems. In this lesson, our goal is to learn how to write formatted table data into a text file using C#, taking advantage of the System.IO namespace and methods like File.WriteAllLines.

By the end of this lesson, you will be able to take a structured data format and write it to a text file using C#. Let’s dive into this skill and build on what you've learned about parsing tables from text and CSV files.

Recall: Basics of Lists and File Handling

Before we proceed, let's briefly recall two key concepts: Lists in C# and basic file handling.

  • Lists: In C#, List<T> allows you to store a collection of items, such as rows in a table. This step is crucial as it helps organize your data into a structured format.

  • File Handling: We have previously covered basic reading operations. Now, we move to writing data. C# provides a straightforward API within the System.IO namespace. Using methods like File.WriteAllLines, we can easily handle file output.

These foundational concepts will guide us in the process of writing table data into a text file.

Structuring Data for Output

First, we'll define the Person class which will serve as the blueprint for our data entries. In this class, each Person object will have properties corresponding to the columns in our table:

C#
1using System; 2using System.Collections.Generic; 3 4class Person 5{ 6 public string? Name { get; set; } 7 public string? Age { get; set; } 8 public string? Occupation { get; set; } 9}

With our structure in place, we can now create a list of Person objects. This list, data, acts as a collection of rows where each Person instance signifies an individual record:

C#
1List<Person> data = new List<Person> 2{ 3 new Person { Name = "John", Age = "28", Occupation = "Engineer" }, 4 new Person { Name = "Alice", Age = "34", Occupation = "Doctor" }, 5 new Person { Name = "Bob", Age = "23", Occupation = "Artist" } 6};

In this example, we've added three Person objects to our list, each representing a row with fields for Name, Age, and Occupation. This structured approach not only simplifies the process of adding or modifying rows but also facilitates the seamless writing of data to files.

Writing Data with Space Delimiters

Now, let's write the data to a text file with spaces as delimiters using C# methods. This example demonstrates the process:

C#
1var outputTxtFilePath = "output.txt"; // Output file path 2 3// Prepare data for space-separated TXT file 4var txtLines = new List<string> { "Name Age Occupation" }; // Header with spaces 5foreach (var person in data) 6{ 7 // Add each person's data as a space-separated line 8 txtLines.Add(string.Join(" ", person.Name, person.Age, person.Occupation)); // Rows with spaces 9} 10 11// Write the list of lines to the TXT file 12File.WriteAllLines(outputTxtFilePath, txtLines); 13Console.WriteLine($"Data successfully written to {outputTxtFilePath} (space-separated).");
  • Define the Output Path: The file path is set for output.txt.
  • Prepare the Header: The header "Name Age Occupation" is added to the txtLines list.
  • Format the Data: Each Person object is converted into a space-delimited line using string.Join(" ", ...).
  • Write to File: File.WriteAllLines writes each line to output.txt, ensuring each entry appears on its own line in the text file.
Writing Data to CSV Format

In addition to writing to a text file with space delimiters, you may also need to write the data in CSV (Comma-Separated Values) format. Here's how you can achieve this in C#:

C#
1var outputCsvFilePath = "output.csv"; // Output file path 2 3// Prepare data for comma-separated CSV file 4var csvLines = new List<string> { "Name,Age,Occupation" }; // Header with commas 5foreach (var person in data) 6{ 7 // Add each person's data as a comma-separated line 8 csvLines.Add(string.Join(",", person.Name, person.Age, person.Occupation)); // Rows with commas 9} 10 11// Write the list of lines to the CSV file 12File.WriteAllLines(outputCsvFilePath, csvLines); 13Console.WriteLine($"Data successfully written to {outputCsvFilePath} (comma-separated).");

As with the space-delimited file, this code writes the csvLines list to output.csv using a comma character as the delimiter, also ensuring each entry is placed on a new line.

Lesson Summary

In this lesson, you learned how to effectively structure, write, and verify data stored in a text file using C#. We started with preparing data using Lists and classes, then utilized C#'s file-handling techniques to write this data using spaces and commas as delimiters.

We encourage you to engage with the practice exercises that follow this lesson. Apply what you've learned to reinforce your understanding and gain confidence. Keep experimenting with different data structures, adapt them, and ensure your outputs meet your expectations. Well done on progressing through this important lesson.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.