File.ReadAllText
File.ReadAllText opens a file, reads all the text inside, and hands it back in one go, like reading a whole letter in one swoop. It is the quickest way to read a small file.
In this page:
Syntax
string content = File.ReadAllText(path);
File.WriteAllText(path, content);
File.ReadAllText
File.ReadAllText reads an entire file into a single string in one call, which is the simplest way to load small-to-medium text files. File.WriteAllText is its counterpart for writing.
Both are static methods on the System.IO.File class and open, use, and close the file automatically.
Note:
For very large files, prefer
StreamReader so you can process the file line by line instead of loading it all into memory.Example: File.ReadAllText
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = "greeting.txt";
File.WriteAllText(path, "Hello from File.WriteAllText!");
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Reading a huge file with
File.ReadAllText, which loads it all into memory. - Using a wrong relative path, so
FileNotFoundExceptionis thrown. - Forgetting to handle
IOExceptionorUnauthorizedAccessException.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: