File.ReadAllText, Get String From File
This page was last reviewed on 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.
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 24, 2022 (edit).
© 2007-2024 Sam Allen.