How to Read and Write a Text File in C#?

Learn via video courses
Topics Covered

Overview

File operations are critical in programming, and C# includes various methods and classes for handling file reading and writing activities. Whether you need to read data from or write data to a text file, C# has a number of built-in methods and classes to make these tasks easier. In this post, we'll look at numerous strategies and classes for reading and writing files in C#.

Read Text File in C#

Read text file in C# involves retrieving the content of a file and processing it. This can be achieved using methods like File.ReadAllText() to read the entire content as a string, or File.ReadAllLines() to read content line by line into an array of strings. Alternatively, the StreamReader class offers greater flexibility for advanced reading operations.

Let us discuss all the methods in detail.

ReadAllText()

File.ReadAllText() in C# is a simple function for reading a text file's complete content as a single string. Because it puts the entire material into memory, this method simplifies file reading processes, especially when dealing with smaller files. However, because to inherent memory limits, it may not be the most efficient alternative for larger files.

Example:

Output:

In this example to read text file in c#, the Main method takes a string array for command-line arguments and reads a specified text file's content using the ReadAllText() method, simplifying the process by loading the entire content into memory. It handles exceptions using try-catch blocks for FileNotFoundException (missing file) and IOException (reading error). After reading, it displays the content using Console.WriteLine(). If errors occur, corresponding error messages are shown. Finally, there's the Console.The ReadLine() statement pauses programme execution and keeps the console window open until the user pushes the Enter key.

ReadAllLines()

The File.ReadAllLines() method in C# offers a straightforward way to read text file in c# line by line. When dealing with files that consist of multiple lines of text, this method is particularly useful. By invoking this method, the content of the file is automatically split into an array of strings, where each string corresponds to a line from the file. This array structure simplifies subsequent processing, such as analyzing or modifying individual lines. However, it's worth noting that this method loads the entire file into memory as an array, which might not be optimal for extremely large files due to potential memory limitations.

Example:

Output:

In this example, the Main method takes an array of strings as input, with filePath storing the targeted text file's path. The program is enclosed in a try block to manage potential file-related exceptions. Within this block, the File.ReadAllLines() method is employed to read all lines from the specified text file and store them in the lines array. Subsequently, a foreach loop iterates through the lines array, enabling the program to display the content line by line. Error handling is integrated to address missing files or read errors, while the program concludes with Console.ReadLine();, awaiting user input before exit to keep the console open.

StreamReader object

In C#, the StreamReader class provides a robust solution for handling increasingly complex file reading operations. It's a useful tool when you need precise control over the reading process. This class provides a variety of methods for reading data not simply character by character or line by line, but also in larger chunks or with specialised character encodings. Because of this increased level of control, the StreamReader class is appropriate for cases requiring the processing of files with complex formats or different needs. This class is especially useful for sophisticated cases, such as parsing structured data or managing files with specific delimiters, because it provides flexibility in how data is retrieved.

Example:

Output:

In this example, the Main method accepts a string array as arguments, using the variable filePath to hold the targeted text file's path. Introducing a StreamReader using a using statement is the key enhancement. This ensures proper disposal of the StreamReader after use. Inside this block, a StreamReader named reader is established, linked to the file path, allowing line-by-line reading. The process employs a while loop, utilizing ReadLine() to iterate through each line. The loop halts when ReadLine() returns null, marking the file's end. Within each cycle, the program displays the line using Console.WriteLine(line)

Write Text File in C#

Write text file in C# is a fundamental operation that involves creating or modifying files with textual content. C# provides various methods and classes to facilitate this process, allowing you to easily write strings or arrays of strings to a text file.

File.WriteAllText()

The File.WriteAllText() function makes it easier to write text files in C# by replacing the existing content with a supplied string. This basic approach is appropriate for situations in which you need to quickly update or create a file with new content. It is crucial to note, however, that this method may not be the best choice for more complex file-writing activities or circumstances in which you need to append data to an existing file.

Example:

Output:

In this example, the code utilizes C#'s File.WriteAllText() method to write a designated string to a text file. After importing necessary namespaces and specifying the file path, the program employs a try-catch block for error handling. The string to be written is defined and then efficiently written to the file using the mentioned method. Upon successful writing, a confirmation message is displayed. The program ensures proper resource management and concludes by allowing the console window to remain open for user interaction.

File.WriteAllLines()

The code employs File.WriteAllText() in C# to write a specific string to a text file. It handles file access and overwrites the file's content with the provided string. Upon success, a confirmation message is shown, and the program concludes by keeping the console open for user interaction.

Example:

Output:

In this example write text file in C#, the code uses the C# method File.WriteAllLines() to write an array of strings as distinct lines to a text file. The program manages file access and writes each string element of the array as a separate line in the file. A confirmation message is presented after successful writing. The program ensures adequate resource management before closing the console window to allow for user input. Replace "path/to/your/file.txt" with the actual file path you want to write to to see the anticipated output.

StreamWriter Object

In C#, the StreamWriter class provides sophisticated features for writing data to files, allowing for complex writing requirements. This class allows you to write data in a variety of formats, manage encoding choices, and even append data to existing files. This adaptability makes the StreamWriter class an excellent fit for tasks requiring more fine-grained control over file writing processes, such as structured data serialisation or incrementally managing big files.

Example

Output:

The code showcases the use of the StreamWriter class to write text file in c#. After importing required namespaces and specifying the file path, the program enters a try-catch block for error handling. The using statement ensures proper resource management as it instantiates a StreamWriter named writer, pointing to the file path. The writer.WriteLine() statements efficiently write two lines of text to the file. Upon successful writing, a confirmation message is displayed. The program concludes by allowing the console window to remain open for user interaction. For the anticipated output, ensure that "path/to/your/file.txt" is replaced with the actual file path you wish to write to.

Conclusion

  • C# provides several methods and objects for read text file in C# and write text file in C#, catering to various requirements and functionality.
  • The File class offers simple methods like ReadAllText() and ReadAllLines() for reading file content, and WriteAllText() and WriteAllLines() for writing content to files.
  • For more advanced reading tasks, the StreamReader class provides methods to read data character by character, line by line, or in larger chunks, granting greater control over the reading process.
  • The StreamWriter class is valuable for complex writing operations, allowing you to write data in different formats, control encoding, and append data to existing files.