Read an entire file to a string with C#
This post will discuss how to read the entire text from a file into a string in C#.
1. Using File.ReadAllText() method (System.IO)
The recommended solution to read all the text in the file into a string is to use the File.ReadAllText() method. The following code example demonstrates its usage to display the contents of a file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; string text = File.ReadAllText(fileName); Console.WriteLine(text); } } |
The File.ReadAllText() method automatically tries to detect the encoding of a file. It has an overloaded version that takes the encoding of the file. It throws an IOException if an I/O error occurs while opening the specified file and FileNotFoundException if the source file is not found.
2. Using StreamReader.ReadToEnd() method (System.IO)
Another solution to read the whole file and copy the file contents to a string is using the StreamReader.ReadToEnd() method.
The following code gets a StreamReader instance using the File.OpenText method and then uses the ReadToEnd() method to read all the way to the end of a file in a single operation. Since the StreamReader object is declared and instantiated in a using statement, the Dispose() method is automatically invoked to flush and closes the stream.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; using (StreamReader streamReader = File.OpenText(fileName)) { string text = streamReader.ReadToEnd(); Console.WriteLine(text); } } } |
The File.OpenText() method opens an existing UTF-8 encoded text file for reading. To open a file with some other character encoding, use the StreamReader class constructor, which optionally takes a specific character encoding.
The following example gets a new StreamReader in ASCII format from a file with byte order mark detection as true:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.IO; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; using (StreamReader streamReader = new StreamReader(fileName, Encoding.ASCII, true)) { string text = streamReader.ReadToEnd(); Console.WriteLine(text); } } } |
That’s all about reading an entire file to a string with C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)