C# File.ReadAllText, Get String From FileUse the File.ReadAllText method from System.IO to get strings from entire files.
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.
Path 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
Caution If that file does not exist, the methods will throw a FileNotFoundException. The program will cease execution.
C# program that reads text files
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.
© 2007-2021 sam allen.
see site info on the changelog.