File.ReadAllText
This C# method reads the entire contents of a text file. This method can often be used instead of StreamReader
. It can simplify some C# programs.
Here we use .NET methods to read text files—this requires the System.IO
namespace. The operation requires only one statement.
The System.IO
namespace is included with the using directive. The two string
references are assigned to the references returned by File.ReadAllText
.
FileNotFoundException
. The program will cease execution.using System; using System.IO; class Program { static void Main() { string value1 = File.ReadAllText("C:\\file.txt"); string value2 = File.ReadAllText(@"C:\file.txt"); Console.WriteLine("--- Contents of file.txt: ---"); Console.WriteLine(value1); Console.WriteLine("--- Contents of file.txt: ---"); Console.WriteLine(value2); } }--- Contents of file.txt: --- (Text) --- Contents of file.txt: --- (Text)
File.ReadAllText
calls into other methods. At some point, low-level functions in Windows read in all the text using buffered reads. The text data is then put into an object.
File.ReadAllText
method then returns a pointer (reference) to this object data.File.ReadAllText
then performs a simple bitwise copy so the variables point to the object data.You will likely need to do more advanced processing of these files at some point. Classes like Path
or Regex
are often helpful.
We looked at how you can read text files and use the contents as a string
. This article showed some basics regarding reading in text files.