Home
C#
File.ReadAllText, Get String From File
Updated Feb 24, 2022
Dot Net Perls
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.
C# method info. Here we use .NET methods to read text files—this requires the System.IO namespace. The operation requires only one statement.
StreamReader
File
Example code. The System.IO namespace is included with the using directive. The two string references are assigned to the references returned by File.ReadAllText.
Detail The path is specified as an absolute path. The file the methods access is located on your "C:\" drive and is named "file.txt."
String Literal
Warning If that file does not exist, the methods will throw a FileNotFoundException. The program will cease execution.
FileNotFoundException
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)
Internals. 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.
Result The File.ReadAllText method then returns a pointer (reference) to this object data.
And The assignment to the result of File.ReadAllText then performs a simple bitwise copy so the variables point to the object data.
A discussion. You will likely need to do more advanced processing of these files at some point. Classes like Path or Regex are often helpful.
Path
Regex File
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 24, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen